

(function universalModuleDefinition(root, factory) {
    var amdDependencies = [];
    var CANNON = root.CANNON || this.CANNON;
    var OIMO = root.OIMO || this.OIMO;
    var earcut = root.earcut || this.earcut;
    if(typeof exports === 'object' && typeof module === 'object') {
         try {  CANNON = CANNON || require("cannon");  } catch(e) {} 
         try {  OIMO = OIMO || require("oimo");  } catch(e) {} 
         try {  earcut = earcut || require("earcut");  } catch(e) {} 

        module.exports = factory(CANNON,OIMO,earcut);
    } else if(typeof define === 'function' && define.amd) {
         if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
         if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
         if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");

        define("babylonjs", amdDependencies, factory);
    } else if(typeof exports === 'object') {
         try {  CANNON = CANNON || require("cannon");  } catch(e) {} 
         try {  OIMO = OIMO || require("oimo");  } catch(e) {} 
         try {  earcut = earcut || require("earcut");  } catch(e) {} 

        exports["babylonjs"] = factory(CANNON,OIMO,earcut);
    } else {
        root["BABYLON"] = factory(CANNON,OIMO,earcut);
    }
})(this, function(CANNON,OIMO,earcut) {
  CANNON = CANNON || this.CANNON;
  OIMO = OIMO || this.OIMO;
  earcut = earcut || this.earcut;

var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
var BABYLON;
(function (BABYLON) {
    /**
     * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
     * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
     */
    var EffectFallbacks = /** @class */ (function () {
        function EffectFallbacks() {
            this._defines = {};
            this._currentRank = 32;
            this._maxRank = -1;
        }
        /**
         * Removes the fallback from the bound mesh.
         */
        EffectFallbacks.prototype.unBindMesh = function () {
            this._mesh = null;
        };
        /**
         * Adds a fallback on the specified property.
         * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
         * @param define The name of the define in the shader
         */
        EffectFallbacks.prototype.addFallback = function (rank, define) {
            if (!this._defines[rank]) {
                if (rank < this._currentRank) {
                    this._currentRank = rank;
                }
                if (rank > this._maxRank) {
                    this._maxRank = rank;
                }
                this._defines[rank] = new Array();
            }
            this._defines[rank].push(define);
        };
        /**
         * Sets the mesh to use CPU skinning when needing to fallback.
         * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
         * @param mesh The mesh to use the fallbacks.
         */
        EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
            this._mesh = mesh;
            if (rank < this._currentRank) {
                this._currentRank = rank;
            }
            if (rank > this._maxRank) {
                this._maxRank = rank;
            }
        };
        Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
            /**
             * Checks to see if more fallbacks are still availible.
             */
            get: function () {
                return this._currentRank <= this._maxRank;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Removes the defines that shoould be removed when falling back.
         * @param currentDefines defines the current define statements for the shader.
         * @param effect defines the current effect we try to compile
         * @returns The resulting defines with defines of the current rank removed.
         */
        EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
            // First we try to switch to CPU skinning
            if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
                this._mesh.computeBonesUsingShaders = false;
                currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
                effect._bonesComputationForcedToCPU = true;
                var scene = this._mesh.getScene();
                for (var index = 0; index < scene.meshes.length; index++) {
                    var otherMesh = scene.meshes[index];
                    if (!otherMesh.material) {
                        continue;
                    }
                    if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
                        continue;
                    }
                    if (otherMesh.material.getEffect() === effect) {
                        otherMesh.computeBonesUsingShaders = false;
                    }
                    else if (otherMesh.subMeshes) {
                        for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
                            var subMesh = _a[_i];
                            var subMeshEffect = subMesh.effect;
                            if (subMeshEffect === effect) {
                                otherMesh.computeBonesUsingShaders = false;
                                break;
                            }
                        }
                    }
                }
            }
            else {
                var currentFallbacks = this._defines[this._currentRank];
                if (currentFallbacks) {
                    for (var index = 0; index < currentFallbacks.length; index++) {
                        currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
                    }
                }
                this._currentRank++;
            }
            return currentDefines;
        };
        return EffectFallbacks;
    }());
    BABYLON.EffectFallbacks = EffectFallbacks;
    /**
     * Options to be used when creating an effect.
     */
    var EffectCreationOptions = /** @class */ (function () {
        function EffectCreationOptions() {
        }
        return EffectCreationOptions;
    }());
    BABYLON.EffectCreationOptions = EffectCreationOptions;
    /**
     * Effect containing vertex and fragment shader that can be executed on an object.
     */
    var Effect = /** @class */ (function () {
        /**
         * Instantiates an effect.
         * An effect can be used to create/manage/execute vertex and fragment shaders.
         * @param baseName Name of the effect.
         * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
         * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
         * @param samplers List of sampler variables that will be passed to the shader.
         * @param engine Engine to be used to render the effect
         * @param defines Define statements to be added to the shader.
         * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
         * @param onCompiled Callback that will be called when the shader is compiled.
         * @param onError Callback that will be called if an error occurs during shader compilation.
         * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
         */
        function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
            if (samplers === void 0) { samplers = null; }
            if (defines === void 0) { defines = null; }
            if (fallbacks === void 0) { fallbacks = null; }
            if (onCompiled === void 0) { onCompiled = null; }
            if (onError === void 0) { onError = null; }
            var _this = this;
            /**
             * Unique ID of the effect.
             */
            this.uniqueId = 0;
            /**
             * Observable that will be called when the shader is compiled.
             */
            this.onCompileObservable = new BABYLON.Observable();
            /**
             * Observable that will be called if an error occurs during shader compilation.
             */
            this.onErrorObservable = new BABYLON.Observable();
            /** @hidden */
            this._bonesComputationForcedToCPU = false;
            this._uniformBuffersNames = {};
            this._isReady = false;
            this._compilationError = "";
            this.name = baseName;
            if (attributesNamesOrOptions.attributes) {
                var options = attributesNamesOrOptions;
                this._engine = uniformsNamesOrEngine;
                this._attributesNames = options.attributes;
                this._uniformsNames = options.uniformsNames.concat(options.samplers);
                this._samplers = options.samplers.slice();
                this.defines = options.defines;
                this.onError = options.onError;
                this.onCompiled = options.onCompiled;
                this._fallbacks = options.fallbacks;
                this._indexParameters = options.indexParameters;
                this._transformFeedbackVaryings = options.transformFeedbackVaryings;
                if (options.uniformBuffersNames) {
                    for (var i = 0; i < options.uniformBuffersNames.length; i++) {
                        this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
                    }
                }
            }
            else {
                this._engine = engine;
                this.defines = defines;
                this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
                this._samplers = samplers ? samplers.slice() : [];
                this._attributesNames = attributesNamesOrOptions;
                this.onError = onError;
                this.onCompiled = onCompiled;
                this._indexParameters = indexParameters;
                this._fallbacks = fallbacks;
            }
            this.uniqueId = Effect._uniqueIdSeed++;
            var vertexSource;
            var fragmentSource;
            if (baseName.vertexElement) {
                vertexSource = document.getElementById(baseName.vertexElement);
                if (!vertexSource) {
                    vertexSource = baseName.vertexElement;
                }
            }
            else {
                vertexSource = baseName.vertex || baseName;
            }
            if (baseName.fragmentElement) {
                fragmentSource = document.getElementById(baseName.fragmentElement);
                if (!fragmentSource) {
                    fragmentSource = baseName.fragmentElement;
                }
            }
            else {
                fragmentSource = baseName.fragment || baseName;
            }
            this._loadVertexShader(vertexSource, function (vertexCode) {
                _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
                    _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
                        _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
                            _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
                                _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
                                    if (baseName) {
                                        var vertex = baseName.vertexElement || baseName.vertex || baseName;
                                        var fragment = baseName.fragmentElement || baseName.fragment || baseName;
                                        _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
                                        _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
                                    }
                                    else {
                                        _this._vertexSourceCode = migratedVertexCode;
                                        _this._fragmentSourceCode = migratedFragmentCode;
                                    }
                                    _this._prepareEffect();
                                });
                            });
                        });
                    });
                });
            });
        }
        Object.defineProperty(Effect.prototype, "onBindObservable", {
            /**
             * Observable that will be called when effect is bound.
             */
            get: function () {
                if (!this._onBindObservable) {
                    this._onBindObservable = new BABYLON.Observable();
                }
                return this._onBindObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Effect.prototype, "key", {
            /**
             * Unique key for this effect
             */
            get: function () {
                return this._key;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * If the effect has been compiled and prepared.
         * @returns if the effect is compiled and prepared.
         */
        Effect.prototype.isReady = function () {
            return this._isReady;
        };
        /**
         * The engine the effect was initialized with.
         * @returns the engine.
         */
        Effect.prototype.getEngine = function () {
            return this._engine;
        };
        /**
         * The compiled webGL program for the effect
         * @returns the webGL program.
         */
        Effect.prototype.getProgram = function () {
            return this._program;
        };
        /**
         * The set of names of attribute variables for the shader.
         * @returns An array of attribute names.
         */
        Effect.prototype.getAttributesNames = function () {
            return this._attributesNames;
        };
        /**
         * Returns the attribute at the given index.
         * @param index The index of the attribute.
         * @returns The location of the attribute.
         */
        Effect.prototype.getAttributeLocation = function (index) {
            return this._attributes[index];
        };
        /**
         * Returns the attribute based on the name of the variable.
         * @param name of the attribute to look up.
         * @returns the attribute location.
         */
        Effect.prototype.getAttributeLocationByName = function (name) {
            var index = this._attributesNames.indexOf(name);
            return this._attributes[index];
        };
        /**
         * The number of attributes.
         * @returns the numnber of attributes.
         */
        Effect.prototype.getAttributesCount = function () {
            return this._attributes.length;
        };
        /**
         * Gets the index of a uniform variable.
         * @param uniformName of the uniform to look up.
         * @returns the index.
         */
        Effect.prototype.getUniformIndex = function (uniformName) {
            return this._uniformsNames.indexOf(uniformName);
        };
        /**
         * Returns the attribute based on the name of the variable.
         * @param uniformName of the uniform to look up.
         * @returns the location of the uniform.
         */
        Effect.prototype.getUniform = function (uniformName) {
            return this._uniforms[this._uniformsNames.indexOf(uniformName)];
        };
        /**
         * Returns an array of sampler variable names
         * @returns The array of sampler variable neames.
         */
        Effect.prototype.getSamplers = function () {
            return this._samplers;
        };
        /**
         * The error from the last compilation.
         * @returns the error string.
         */
        Effect.prototype.getCompilationError = function () {
            return this._compilationError;
        };
        /**
         * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
         * @param func The callback to be used.
         */
        Effect.prototype.executeWhenCompiled = function (func) {
            if (this.isReady()) {
                func(this);
                return;
            }
            this.onCompileObservable.add(function (effect) {
                func(effect);
            });
        };
        /** @hidden */
        Effect.prototype._loadVertexShader = function (vertex, callback) {
            if (BABYLON.Tools.IsWindowObjectExist()) {
                // DOM element ?
                if (vertex instanceof HTMLElement) {
                    var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
                    callback(vertexCode);
                    return;
                }
            }
            // Base64 encoded ?
            if (vertex.substr(0, 7) === "base64:") {
                var vertexBinary = window.atob(vertex.substr(7));
                callback(vertexBinary);
                return;
            }
            // Is in local store ?
            if (Effect.ShadersStore[vertex + "VertexShader"]) {
                callback(Effect.ShadersStore[vertex + "VertexShader"]);
                return;
            }
            var vertexShaderUrl;
            if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
                vertexShaderUrl = vertex;
            }
            else {
                vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
            }
            // Vertex shader
            this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
        };
        /** @hidden */
        Effect.prototype._loadFragmentShader = function (fragment, callback) {
            if (BABYLON.Tools.IsWindowObjectExist()) {
                // DOM element ?
                if (fragment instanceof HTMLElement) {
                    var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
                    callback(fragmentCode);
                    return;
                }
            }
            // Base64 encoded ?
            if (fragment.substr(0, 7) === "base64:") {
                var fragmentBinary = window.atob(fragment.substr(7));
                callback(fragmentBinary);
                return;
            }
            // Is in local store ?
            if (Effect.ShadersStore[fragment + "PixelShader"]) {
                callback(Effect.ShadersStore[fragment + "PixelShader"]);
                return;
            }
            if (Effect.ShadersStore[fragment + "FragmentShader"]) {
                callback(Effect.ShadersStore[fragment + "FragmentShader"]);
                return;
            }
            var fragmentShaderUrl;
            if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
                fragmentShaderUrl = fragment;
            }
            else {
                fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
            }
            // Fragment shader
            this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
        };
        /** @hidden */
        Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
            // Rebuild shaders source code
            var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
            var prefix = shaderVersion + (defines ? defines + "\n" : "");
            vertexCode = prefix + vertexCode;
            fragmentCode = prefix + fragmentCode;
            // Number lines of shaders source code
            var i = 2;
            var regex = /\n/gm;
            var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
            i = 2;
            var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
            // Dump shaders name and formatted source code
            if (this.name.vertexElement) {
                BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
                BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
            }
            else if (this.name.vertex) {
                BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
                BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
            }
            else {
                BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
                BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
            }
        };
        Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
            var preparedSourceCode = this._processPrecision(sourceCode);
            if (this._engine.webGLVersion == 1) {
                callback(preparedSourceCode);
                return;
            }
            // Already converted
            if (preparedSourceCode.indexOf("#version 3") !== -1) {
                callback(preparedSourceCode.replace("#version 300 es", ""));
                return;
            }
            var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
            // Remove extensions
            // #extension GL_OES_standard_derivatives : enable
            // #extension GL_EXT_shader_texture_lod : enable
            // #extension GL_EXT_frag_depth : enable
            // #extension GL_EXT_draw_buffers : require
            var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
            var result = preparedSourceCode.replace(regex, "");
            // Migrate to GLSL v300
            result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
            result = result.replace(/attribute[ \t]/g, "in ");
            result = result.replace(/[ \t]attribute/g, " in");
            if (isFragment) {
                result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
                result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
                result = result.replace(/texture2D\s*\(/g, "texture(");
                result = result.replace(/textureCube\s*\(/g, "texture(");
                result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
                result = result.replace(/gl_FragColor/g, "glFragColor");
                result = result.replace(/gl_FragData/g, "glFragData");
                result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
            }
            callback(result);
        };
        Effect.prototype._processIncludes = function (sourceCode, callback) {
            var _this = this;
            var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
            var match = regex.exec(sourceCode);
            var returnValue = new String(sourceCode);
            while (match != null) {
                var includeFile = match[1];
                // Uniform declaration
                if (includeFile.indexOf("__decl__") !== -1) {
                    includeFile = includeFile.replace(/__decl__/, "");
                    if (this._engine.supportsUniformBuffers) {
                        includeFile = includeFile.replace(/Vertex/, "Ubo");
                        includeFile = includeFile.replace(/Fragment/, "Ubo");
                    }
                    includeFile = includeFile + "Declaration";
                }
                if (Effect.IncludesShadersStore[includeFile]) {
                    // Substitution
                    var includeContent = Effect.IncludesShadersStore[includeFile];
                    if (match[2]) {
                        var splits = match[3].split(",");
                        for (var index = 0; index < splits.length; index += 2) {
                            var source = new RegExp(splits[index], "g");
                            var dest = splits[index + 1];
                            includeContent = includeContent.replace(source, dest);
                        }
                    }
                    if (match[4]) {
                        var indexString = match[5];
                        if (indexString.indexOf("..") !== -1) {
                            var indexSplits = indexString.split("..");
                            var minIndex = parseInt(indexSplits[0]);
                            var maxIndex = parseInt(indexSplits[1]);
                            var sourceIncludeContent = includeContent.slice(0);
                            includeContent = "";
                            if (isNaN(maxIndex)) {
                                maxIndex = this._indexParameters[indexSplits[1]];
                            }
                            for (var i = minIndex; i < maxIndex; i++) {
                                if (!this._engine.supportsUniformBuffers) {
                                    // Ubo replacement
                                    sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
                                        return p1 + "{X}";
                                    });
                                }
                                includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
                            }
                        }
                        else {
                            if (!this._engine.supportsUniformBuffers) {
                                // Ubo replacement
                                includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
                                    return p1 + "{X}";
                                });
                            }
                            includeContent = includeContent.replace(/\{X\}/g, indexString);
                        }
                    }
                    // Replace
                    returnValue = returnValue.replace(match[0], includeContent);
                }
                else {
                    var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
                    this._engine._loadFile(includeShaderUrl, function (fileContent) {
                        Effect.IncludesShadersStore[includeFile] = fileContent;
                        _this._processIncludes(returnValue, callback);
                    });
                    return;
                }
                match = regex.exec(sourceCode);
            }
            callback(returnValue);
        };
        Effect.prototype._processPrecision = function (source) {
            if (source.indexOf("precision highp float") === -1) {
                if (!this._engine.getCaps().highPrecisionShaderSupported) {
                    source = "precision mediump float;\n" + source;
                }
                else {
                    source = "precision highp float;\n" + source;
                }
            }
            else {
                if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
                    source = source.replace("precision highp float", "precision mediump float");
                }
            }
            return source;
        };
        /**
         * Recompiles the webGL program
         * @param vertexSourceCode The source code for the vertex shader.
         * @param fragmentSourceCode The source code for the fragment shader.
         * @param onCompiled Callback called when completed.
         * @param onError Callback called on error.
         * @hidden
         */
        Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
            var _this = this;
            this._isReady = false;
            this._vertexSourceCodeOverride = vertexSourceCode;
            this._fragmentSourceCodeOverride = fragmentSourceCode;
            this.onError = function (effect, error) {
                if (onError) {
                    onError(error);
                }
            };
            this.onCompiled = function () {
                var scenes = _this.getEngine().scenes;
                for (var i = 0; i < scenes.length; i++) {
                    scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
                }
                if (onCompiled) {
                    onCompiled(_this._program);
                }
            };
            this._fallbacks = null;
            this._prepareEffect();
        };
        /**
         * Gets the uniform locations of the the specified variable names
         * @param names THe names of the variables to lookup.
         * @returns Array of locations in the same order as variable names.
         */
        Effect.prototype.getSpecificUniformLocations = function (names) {
            var engine = this._engine;
            return engine.getUniforms(this._program, names);
        };
        /**
         * Prepares the effect
         * @hidden
         */
        Effect.prototype._prepareEffect = function () {
            var attributesNames = this._attributesNames;
            var defines = this.defines;
            var fallbacks = this._fallbacks;
            this._valueCache = {};
            var previousProgram = this._program;
            try {
                var engine = this._engine;
                if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
                    this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
                }
                else {
                    this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
                }
                this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
                if (engine.supportsUniformBuffers) {
                    for (var name in this._uniformBuffersNames) {
                        this.bindUniformBlock(name, this._uniformBuffersNames[name]);
                    }
                }
                this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
                this._attributes = engine.getAttributes(this._program, attributesNames);
                var index;
                for (index = 0; index < this._samplers.length; index++) {
                    var sampler = this.getUniform(this._samplers[index]);
                    if (sampler == null) {
                        this._samplers.splice(index, 1);
                        index--;
                    }
                }
                engine.bindSamplers(this);
                this._compilationError = "";
                this._isReady = true;
                if (this.onCompiled) {
                    this.onCompiled(this);
                }
                this.onCompileObservable.notifyObservers(this);
                this.onCompileObservable.clear();
                // Unbind mesh reference in fallbacks
                if (this._fallbacks) {
                    this._fallbacks.unBindMesh();
                }
                if (previousProgram) {
                    this.getEngine()._deleteProgram(previousProgram);
                }
            }
            catch (e) {
                this._compilationError = e.message;
                // Let's go through fallbacks then
                BABYLON.Tools.Error("Unable to compile effect:");
                BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
                    return " " + uniform;
                }));
                BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
                    return " " + attribute;
                }));
                BABYLON.Tools.Error("Error: " + this._compilationError);
                if (previousProgram) {
                    this._program = previousProgram;
                    this._isReady = true;
                    if (this.onError) {
                        this.onError(this, this._compilationError);
                    }
                    this.onErrorObservable.notifyObservers(this);
                }
                if (fallbacks && fallbacks.isMoreFallbacks) {
                    BABYLON.Tools.Error("Trying next fallback.");
                    this.defines = fallbacks.reduce(this.defines, this);
                    this._prepareEffect();
                }
                else { // Sorry we did everything we can
                    if (this.onError) {
                        this.onError(this, this._compilationError);
                    }
                    this.onErrorObservable.notifyObservers(this);
                    this.onErrorObservable.clear();
                    // Unbind mesh reference in fallbacks
                    if (this._fallbacks) {
                        this._fallbacks.unBindMesh();
                    }
                }
            }
        };
        Object.defineProperty(Effect.prototype, "isSupported", {
            /**
             * Checks if the effect is supported. (Must be called after compilation)
             */
            get: function () {
                return this._compilationError === "";
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Binds a texture to the engine to be used as output of the shader.
         * @param channel Name of the output variable.
         * @param texture Texture to bind.
         * @hidden
         */
        Effect.prototype._bindTexture = function (channel, texture) {
            this._engine._bindTexture(this._samplers.indexOf(channel), texture);
        };
        /**
         * Sets a texture on the engine to be used in the shader.
         * @param channel Name of the sampler variable.
         * @param texture Texture to set.
         */
        Effect.prototype.setTexture = function (channel, texture) {
            this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
        };
        /**
         * Sets a depth stencil texture from a render target on the engine to be used in the shader.
         * @param channel Name of the sampler variable.
         * @param texture Texture to set.
         */
        Effect.prototype.setDepthStencilTexture = function (channel, texture) {
            this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
        };
        /**
         * Sets an array of textures on the engine to be used in the shader.
         * @param channel Name of the variable.
         * @param textures Textures to set.
         */
        Effect.prototype.setTextureArray = function (channel, textures) {
            if (this._samplers.indexOf(channel + "Ex") === -1) {
                var initialPos = this._samplers.indexOf(channel);
                for (var index = 1; index < textures.length; index++) {
                    this._samplers.splice(initialPos + index, 0, channel + "Ex");
                }
            }
            this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
        };
        /**
         * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
         * @param channel Name of the sampler variable.
         * @param postProcess Post process to get the input texture from.
         */
        Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
            this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
        };
        /**
         * (Warning! setTextureFromPostProcessOutput may be desired instead)
         * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
         * @param channel Name of the sampler variable.
         * @param postProcess Post process to get the output texture from.
         */
        Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
            this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
        };
        /** @hidden */
        Effect.prototype._cacheMatrix = function (uniformName, matrix) {
            var cache = this._valueCache[uniformName];
            var flag = matrix.updateFlag;
            if (cache !== undefined && cache === flag) {
                return false;
            }
            this._valueCache[uniformName] = flag;
            return true;
        };
        /** @hidden */
        Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
            var cache = this._valueCache[uniformName];
            if (!cache) {
                cache = [x, y];
                this._valueCache[uniformName] = cache;
                return true;
            }
            var changed = false;
            if (cache[0] !== x) {
                cache[0] = x;
                changed = true;
            }
            if (cache[1] !== y) {
                cache[1] = y;
                changed = true;
            }
            return changed;
        };
        /** @hidden */
        Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
            var cache = this._valueCache[uniformName];
            if (!cache) {
                cache = [x, y, z];
                this._valueCache[uniformName] = cache;
                return true;
            }
            var changed = false;
            if (cache[0] !== x) {
                cache[0] = x;
                changed = true;
            }
            if (cache[1] !== y) {
                cache[1] = y;
                changed = true;
            }
            if (cache[2] !== z) {
                cache[2] = z;
                changed = true;
            }
            return changed;
        };
        /** @hidden */
        Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
            var cache = this._valueCache[uniformName];
            if (!cache) {
                cache = [x, y, z, w];
                this._valueCache[uniformName] = cache;
                return true;
            }
            var changed = false;
            if (cache[0] !== x) {
                cache[0] = x;
                changed = true;
            }
            if (cache[1] !== y) {
                cache[1] = y;
                changed = true;
            }
            if (cache[2] !== z) {
                cache[2] = z;
                changed = true;
            }
            if (cache[3] !== w) {
                cache[3] = w;
                changed = true;
            }
            return changed;
        };
        /**
         * Binds a buffer to a uniform.
         * @param buffer Buffer to bind.
         * @param name Name of the uniform variable to bind to.
         */
        Effect.prototype.bindUniformBuffer = function (buffer, name) {
            var bufferName = this._uniformBuffersNames[name];
            if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
                return;
            }
            Effect._baseCache[bufferName] = buffer;
            this._engine.bindUniformBufferBase(buffer, bufferName);
        };
        /**
         * Binds block to a uniform.
         * @param blockName Name of the block to bind.
         * @param index Index to bind.
         */
        Effect.prototype.bindUniformBlock = function (blockName, index) {
            this._engine.bindUniformBlock(this._program, blockName, index);
        };
        /**
         * Sets an interger value on a uniform variable.
         * @param uniformName Name of the variable.
         * @param value Value to be set.
         * @returns this effect.
         */
        Effect.prototype.setInt = function (uniformName, value) {
            var cache = this._valueCache[uniformName];
            if (cache !== undefined && cache === value) {
                return this;
            }
            this._valueCache[uniformName] = value;
            this._engine.setInt(this.getUniform(uniformName), value);
            return this;
        };
        /**
         * Sets an int array on a uniform variable.
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setIntArray = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setIntArray2 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray2(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setIntArray3 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray3(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setIntArray4 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setIntArray4(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an float array on a uniform variable.
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setFloatArray = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setFloatArray2 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray2(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setFloatArray3 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray3(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setFloatArray4 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setFloatArray4(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an array on a uniform variable.
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setArray = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setArray2 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray2(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setArray3 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray3(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
         * @param uniformName Name of the variable.
         * @param array array to be set.
         * @returns this effect.
         */
        Effect.prototype.setArray4 = function (uniformName, array) {
            this._valueCache[uniformName] = null;
            this._engine.setArray4(this.getUniform(uniformName), array);
            return this;
        };
        /**
         * Sets matrices on a uniform variable.
         * @param uniformName Name of the variable.
         * @param matrices matrices to be set.
         * @returns this effect.
         */
        Effect.prototype.setMatrices = function (uniformName, matrices) {
            if (!matrices) {
                return this;
            }
            this._valueCache[uniformName] = null;
            this._engine.setMatrices(this.getUniform(uniformName), matrices);
            return this;
        };
        /**
         * Sets matrix on a uniform variable.
         * @param uniformName Name of the variable.
         * @param matrix matrix to be set.
         * @returns this effect.
         */
        Effect.prototype.setMatrix = function (uniformName, matrix) {
            if (this._cacheMatrix(uniformName, matrix)) {
                this._engine.setMatrix(this.getUniform(uniformName), matrix);
            }
            return this;
        };
        /**
         * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
         * @param uniformName Name of the variable.
         * @param matrix matrix to be set.
         * @returns this effect.
         */
        Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
            this._valueCache[uniformName] = null;
            this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
            return this;
        };
        /**
         * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
         * @param uniformName Name of the variable.
         * @param matrix matrix to be set.
         * @returns this effect.
         */
        Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
            this._valueCache[uniformName] = null;
            this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
            return this;
        };
        /**
         * Sets a float on a uniform variable.
         * @param uniformName Name of the variable.
         * @param value value to be set.
         * @returns this effect.
         */
        Effect.prototype.setFloat = function (uniformName, value) {
            var cache = this._valueCache[uniformName];
            if (cache !== undefined && cache === value) {
                return this;
            }
            this._valueCache[uniformName] = value;
            this._engine.setFloat(this.getUniform(uniformName), value);
            return this;
        };
        /**
         * Sets a boolean on a uniform variable.
         * @param uniformName Name of the variable.
         * @param bool value to be set.
         * @returns this effect.
         */
        Effect.prototype.setBool = function (uniformName, bool) {
            var cache = this._valueCache[uniformName];
            if (cache !== undefined && cache === bool) {
                return this;
            }
            this._valueCache[uniformName] = bool;
            this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
            return this;
        };
        /**
         * Sets a Vector2 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param vector2 vector2 to be set.
         * @returns this effect.
         */
        Effect.prototype.setVector2 = function (uniformName, vector2) {
            if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
                this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
            }
            return this;
        };
        /**
         * Sets a float2 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param x First float in float2.
         * @param y Second float in float2.
         * @returns this effect.
         */
        Effect.prototype.setFloat2 = function (uniformName, x, y) {
            if (this._cacheFloat2(uniformName, x, y)) {
                this._engine.setFloat2(this.getUniform(uniformName), x, y);
            }
            return this;
        };
        /**
         * Sets a Vector3 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param vector3 Value to be set.
         * @returns this effect.
         */
        Effect.prototype.setVector3 = function (uniformName, vector3) {
            if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
                this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
            }
            return this;
        };
        /**
         * Sets a float3 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param x First float in float3.
         * @param y Second float in float3.
         * @param z Third float in float3.
         * @returns this effect.
         */
        Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
            if (this._cacheFloat3(uniformName, x, y, z)) {
                this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
            }
            return this;
        };
        /**
         * Sets a Vector4 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param vector4 Value to be set.
         * @returns this effect.
         */
        Effect.prototype.setVector4 = function (uniformName, vector4) {
            if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
                this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
            }
            return this;
        };
        /**
         * Sets a float4 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param x First float in float4.
         * @param y Second float in float4.
         * @param z Third float in float4.
         * @param w Fourth float in float4.
         * @returns this effect.
         */
        Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
            if (this._cacheFloat4(uniformName, x, y, z, w)) {
                this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
            }
            return this;
        };
        /**
         * Sets a Color3 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param color3 Value to be set.
         * @returns this effect.
         */
        Effect.prototype.setColor3 = function (uniformName, color3) {
            if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
                this._engine.setColor3(this.getUniform(uniformName), color3);
            }
            return this;
        };
        /**
         * Sets a Color4 on a uniform variable.
         * @param uniformName Name of the variable.
         * @param color3 Value to be set.
         * @param alpha Alpha value to be set.
         * @returns this effect.
         */
        Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
            if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
                this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
            }
            return this;
        };
        /**
         * Sets a Color4 on a uniform variable
         * @param uniformName defines the name of the variable
         * @param color4 defines the value to be set
         * @returns this effect.
         */
        Effect.prototype.setDirectColor4 = function (uniformName, color4) {
            if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
                this._engine.setDirectColor4(this.getUniform(uniformName), color4);
            }
            return this;
        };
        /**
         * This function will add a new shader to the shader store
         * @param name the name of the shader
         * @param pixelShader optional pixel shader content
         * @param vertexShader optional vertex shader content
         */
        Effect.RegisterShader = function (name, pixelShader, vertexShader) {
            if (pixelShader) {
                Effect.ShadersStore[name + "PixelShader"] = pixelShader;
            }
            if (vertexShader) {
                Effect.ShadersStore[name + "VertexShader"] = vertexShader;
            }
        };
        /**
         * Resets the cache of effects.
         */
        Effect.ResetCache = function () {
            Effect._baseCache = {};
        };
        Effect._uniqueIdSeed = 0;
        Effect._baseCache = {};
        /**
         * Store of each shader (The can be looked up using effect.key)
         */
        Effect.ShadersStore = {};
        /**
         * Store of each included file for a shader (The can be looked up using effect.key)
         */
        Effect.IncludesShadersStore = {};
        return Effect;
    }());
    BABYLON.Effect = Effect;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.effect.js.map



//# sourceMappingURL=babylon.types.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Gather the list of keyboard event types as constants.
     */
    var KeyboardEventTypes = /** @class */ (function () {
        function KeyboardEventTypes() {
        }
        /**
         * The keydown event is fired when a key becomes active (pressed).
         */
        KeyboardEventTypes.KEYDOWN = 0x01;
        /**
         * The keyup event is fired when a key has been released.
         */
        KeyboardEventTypes.KEYUP = 0x02;
        return KeyboardEventTypes;
    }());
    BABYLON.KeyboardEventTypes = KeyboardEventTypes;
    /**
     * This class is used to store keyboard related info for the onKeyboardObservable event.
     */
    var KeyboardInfo = /** @class */ (function () {
        /**
         * Instantiates a new keyboard info.
         * This class is used to store keyboard related info for the onKeyboardObservable event.
         * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
         * @param event Defines the related dom event
         */
        function KeyboardInfo(
        /**
         * Defines the type of event (BABYLON.KeyboardEventTypes)
         */
        type, 
        /**
         * Defines the related dom event
         */
        event) {
            this.type = type;
            this.event = event;
        }
        return KeyboardInfo;
    }());
    BABYLON.KeyboardInfo = KeyboardInfo;
    /**
     * This class is used to store keyboard related info for the onPreKeyboardObservable event.
     * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
     */
    var KeyboardInfoPre = /** @class */ (function (_super) {
        __extends(KeyboardInfoPre, _super);
        /**
         * Instantiates a new keyboard pre info.
         * This class is used to store keyboard related info for the onPreKeyboardObservable event.
         * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
         * @param event Defines the related dom event
         */
        function KeyboardInfoPre(
        /**
         * Defines the type of event (BABYLON.KeyboardEventTypes)
         */
        type, 
        /**
         * Defines the related dom event
         */
        event) {
            var _this = _super.call(this, type, event) || this;
            _this.type = type;
            _this.event = event;
            _this.skipOnPointerObservable = false;
            return _this;
        }
        return KeyboardInfoPre;
    }(KeyboardInfo));
    BABYLON.KeyboardInfoPre = KeyboardInfoPre;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.keyboardEvents.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Gather the list of pointer event types as constants.
     */
    var PointerEventTypes = /** @class */ (function () {
        function PointerEventTypes() {
        }
        /**
         * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
         */
        PointerEventTypes.POINTERDOWN = 0x01;
        /**
         * The pointerup event is fired when a pointer is no longer active.
         */
        PointerEventTypes.POINTERUP = 0x02;
        /**
         * The pointermove event is fired when a pointer changes coordinates.
         */
        PointerEventTypes.POINTERMOVE = 0x04;
        /**
         * The pointerwheel event is fired when a mouse wheel has been rotated.
         */
        PointerEventTypes.POINTERWHEEL = 0x08;
        /**
         * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
         */
        PointerEventTypes.POINTERPICK = 0x10;
        /**
         * The pointertap event is fired when a the object has been touched and released without drag.
         */
        PointerEventTypes.POINTERTAP = 0x20;
        /**
         * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
         */
        PointerEventTypes.POINTERDOUBLETAP = 0x40;
        return PointerEventTypes;
    }());
    BABYLON.PointerEventTypes = PointerEventTypes;
    /**
     * Base class of pointer info types.
     */
    var PointerInfoBase = /** @class */ (function () {
        /**
         * Instantiates the base class of pointers info.
         * @param type Defines the type of event (BABYLON.PointerEventTypes)
         * @param event Defines the related dom event
         */
        function PointerInfoBase(
        /**
         * Defines the type of event (BABYLON.PointerEventTypes)
         */
        type, 
        /**
         * Defines the related dom event
         */
        event) {
            this.type = type;
            this.event = event;
        }
        return PointerInfoBase;
    }());
    BABYLON.PointerInfoBase = PointerInfoBase;
    /**
     * This class is used to store pointer related info for the onPrePointerObservable event.
     * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
     */
    var PointerInfoPre = /** @class */ (function (_super) {
        __extends(PointerInfoPre, _super);
        /**
         * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
         * @param type Defines the type of event (BABYLON.PointerEventTypes)
         * @param event Defines the related dom event
         * @param localX Defines the local x coordinates of the pointer when the event occured
         * @param localY Defines the local y coordinates of the pointer when the event occured
         */
        function PointerInfoPre(type, event, localX, localY) {
            var _this = _super.call(this, type, event) || this;
            /**
             * Ray from a pointer if availible (eg. 6dof controller)
             */
            _this.ray = null;
            _this.skipOnPointerObservable = false;
            _this.localPosition = new BABYLON.Vector2(localX, localY);
            return _this;
        }
        return PointerInfoPre;
    }(PointerInfoBase));
    BABYLON.PointerInfoPre = PointerInfoPre;
    /**
     * This type contains all the data related to a pointer event in Babylon.js.
     * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
     */
    var PointerInfo = /** @class */ (function (_super) {
        __extends(PointerInfo, _super);
        /**
         * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
         * @param type Defines the type of event (BABYLON.PointerEventTypes)
         * @param event Defines the related dom event
         * @param pickInfo Defines the picking info associated to the info (if any)\
         */
        function PointerInfo(type, event, 
        /**
         * Defines the picking info associated to the info (if any)\
         */
        pickInfo) {
            var _this = _super.call(this, type, event) || this;
            _this.pickInfo = pickInfo;
            return _this;
        }
        return PointerInfo;
    }(PointerInfoBase));
    BABYLON.PointerInfo = PointerInfo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pointerEvents.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Constant used to convert a value to gamma space
     * @ignorenaming
     */
    BABYLON.ToGammaSpace = 1 / 2.2;
    /**
     * Constant used to convert a value to linear space
     * @ignorenaming
     */
    BABYLON.ToLinearSpace = 2.2;
    /**
     * Constant used to define the minimal number value in Babylon.js
     * @ignorenaming
     */
    BABYLON.Epsilon = 0.001;
    /**
     * Class used to hold a RBG color
     */
    var Color3 = /** @class */ (function () {
        /**
         * Creates a new Color3 object from red, green, blue values, all between 0 and 1
         * @param r defines the red component (between 0 and 1, default is 0)
         * @param g defines the green component (between 0 and 1, default is 0)
         * @param b defines the blue component (between 0 and 1, default is 0)
         */
        function Color3(
        /**
         * Defines the red component (between 0 and 1, default is 0)
         */
        r, 
        /**
         * Defines the green component (between 0 and 1, default is 0)
         */
        g, 
        /**
         * Defines the blue component (between 0 and 1, default is 0)
         */
        b) {
            if (r === void 0) { r = 0; }
            if (g === void 0) { g = 0; }
            if (b === void 0) { b = 0; }
            this.r = r;
            this.g = g;
            this.b = b;
        }
        /**
         * Creates a string with the Color3 current values
         * @returns the string representation of the Color3 object
         */
        Color3.prototype.toString = function () {
            return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
        };
        /**
         * Returns the string "Color3"
         * @returns "Color3"
         */
        Color3.prototype.getClassName = function () {
            return "Color3";
        };
        /**
         * Compute the Color3 hash code
         * @returns an unique number that can be used to hash Color3 objects
         */
        Color3.prototype.getHashCode = function () {
            var hash = this.r || 0;
            hash = (hash * 397) ^ (this.g || 0);
            hash = (hash * 397) ^ (this.b || 0);
            return hash;
        };
        // Operators
        /**
         * Stores in the given array from the given starting index the red, green, blue values as successive elements
         * @param array defines the array where to store the r,g,b components
         * @param index defines an optional index in the target array to define where to start storing values
         * @returns the current Color3 object
         */
        Color3.prototype.toArray = function (array, index) {
            if (index === undefined) {
                index = 0;
            }
            array[index] = this.r;
            array[index + 1] = this.g;
            array[index + 2] = this.b;
            return this;
        };
        /**
         * Returns a new Color4 object from the current Color3 and the given alpha
         * @param alpha defines the alpha component on the new Color4 object (default is 1)
         * @returns a new Color4 object
         */
        Color3.prototype.toColor4 = function (alpha) {
            if (alpha === void 0) { alpha = 1; }
            return new Color4(this.r, this.g, this.b, alpha);
        };
        /**
         * Returns a new array populated with 3 numeric elements : red, green and blue values
         * @returns the new array
         */
        Color3.prototype.asArray = function () {
            var result = new Array();
            this.toArray(result, 0);
            return result;
        };
        /**
         * Returns the luminance value
         * @returns a float value
         */
        Color3.prototype.toLuminance = function () {
            return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
        };
        /**
         * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
         * @param otherColor defines the second operand
         * @returns the new Color3 object
         */
        Color3.prototype.multiply = function (otherColor) {
            return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
        };
        /**
         * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
         * @param otherColor defines the second operand
         * @param result defines the Color3 object where to store the result
         * @returns the current Color3
         */
        Color3.prototype.multiplyToRef = function (otherColor, result) {
            result.r = this.r * otherColor.r;
            result.g = this.g * otherColor.g;
            result.b = this.b * otherColor.b;
            return this;
        };
        /**
         * Determines equality between Color3 objects
         * @param otherColor defines the second operand
         * @returns true if the rgb values are equal to the given ones
         */
        Color3.prototype.equals = function (otherColor) {
            return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
        };
        /**
         * Determines equality between the current Color3 object and a set of r,b,g values
         * @param r defines the red component to check
         * @param g defines the green component to check
         * @param b defines the blue component to check
         * @returns true if the rgb values are equal to the given ones
         */
        Color3.prototype.equalsFloats = function (r, g, b) {
            return this.r === r && this.g === g && this.b === b;
        };
        /**
         * Multiplies in place each rgb value by scale
         * @param scale defines the scaling factor
         * @returns the updated Color3
         */
        Color3.prototype.scale = function (scale) {
            return new Color3(this.r * scale, this.g * scale, this.b * scale);
        };
        /**
         * Multiplies the rgb values by scale and stores the result into "result"
         * @param scale defines the scaling factor
         * @param result defines the Color3 object where to store the result
         * @returns the unmodified current Color3
         */
        Color3.prototype.scaleToRef = function (scale, result) {
            result.r = this.r * scale;
            result.g = this.g * scale;
            result.b = this.b * scale;
            return this;
        };
        /**
         * Scale the current Color3 values by a factor and add the result to a given Color3
         * @param scale defines the scale factor
         * @param result defines color to store the result into
         * @returns the unmodified current Color3
         */
        Color3.prototype.scaleAndAddToRef = function (scale, result) {
            result.r += this.r * scale;
            result.g += this.g * scale;
            result.b += this.b * scale;
            return this;
        };
        /**
         * Clamps the rgb values by the min and max values and stores the result into "result"
         * @param min defines minimum clamping value (default is 0)
         * @param max defines maximum clamping value (default is 1)
         * @param result defines color to store the result into
         * @returns the original Color3
         */
        Color3.prototype.clampToRef = function (min, max, result) {
            if (min === void 0) { min = 0; }
            if (max === void 0) { max = 1; }
            result.r = BABYLON.Scalar.Clamp(this.r, min, max);
            result.g = BABYLON.Scalar.Clamp(this.g, min, max);
            result.b = BABYLON.Scalar.Clamp(this.b, min, max);
            return this;
        };
        /**
         * Creates a new Color3 set with the added values of the current Color3 and of the given one
         * @param otherColor defines the second operand
         * @returns the new Color3
         */
        Color3.prototype.add = function (otherColor) {
            return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
        };
        /**
         * Stores the result of the addition of the current Color3 and given one rgb values into "result"
         * @param otherColor defines the second operand
         * @param result defines Color3 object to store the result into
         * @returns the unmodified current Color3
         */
        Color3.prototype.addToRef = function (otherColor, result) {
            result.r = this.r + otherColor.r;
            result.g = this.g + otherColor.g;
            result.b = this.b + otherColor.b;
            return this;
        };
        /**
         * Returns a new Color3 set with the subtracted values of the given one from the current Color3
         * @param otherColor defines the second operand
         * @returns the new Color3
         */
        Color3.prototype.subtract = function (otherColor) {
            return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
        };
        /**
         * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
         * @param otherColor defines the second operand
         * @param result defines Color3 object to store the result into
         * @returns the unmodified current Color3
         */
        Color3.prototype.subtractToRef = function (otherColor, result) {
            result.r = this.r - otherColor.r;
            result.g = this.g - otherColor.g;
            result.b = this.b - otherColor.b;
            return this;
        };
        /**
         * Copy the current object
         * @returns a new Color3 copied the current one
         */
        Color3.prototype.clone = function () {
            return new Color3(this.r, this.g, this.b);
        };
        /**
         * Copies the rgb values from the source in the current Color3
         * @param source defines the source Color3 object
         * @returns the updated Color3 object
         */
        Color3.prototype.copyFrom = function (source) {
            this.r = source.r;
            this.g = source.g;
            this.b = source.b;
            return this;
        };
        /**
         * Updates the Color3 rgb values from the given floats
         * @param r defines the red component to read from
         * @param g defines the green component to read from
         * @param b defines the blue component to read from
         * @returns the current Color3 object
         */
        Color3.prototype.copyFromFloats = function (r, g, b) {
            this.r = r;
            this.g = g;
            this.b = b;
            return this;
        };
        /**
         * Updates the Color3 rgb values from the given floats
         * @param r defines the red component to read from
         * @param g defines the green component to read from
         * @param b defines the blue component to read from
         * @returns the current Color3 object
         */
        Color3.prototype.set = function (r, g, b) {
            return this.copyFromFloats(r, g, b);
        };
        /**
         * Compute the Color3 hexadecimal code as a string
         * @returns a string containing the hexadecimal representation of the Color3 object
         */
        Color3.prototype.toHexString = function () {
            var intR = (this.r * 255) | 0;
            var intG = (this.g * 255) | 0;
            var intB = (this.b * 255) | 0;
            return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
        };
        /**
         * Computes a new Color3 converted from the current one to linear space
         * @returns a new Color3 object
         */
        Color3.prototype.toLinearSpace = function () {
            var convertedColor = new Color3();
            this.toLinearSpaceToRef(convertedColor);
            return convertedColor;
        };
        /**
         * Converts the Color3 values to linear space and stores the result in "convertedColor"
         * @param convertedColor defines the Color3 object where to store the linear space version
         * @returns the unmodified Color3
         */
        Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
            convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
            convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
            convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
            return this;
        };
        /**
         * Computes a new Color3 converted from the current one to gamma space
         * @returns a new Color3 object
         */
        Color3.prototype.toGammaSpace = function () {
            var convertedColor = new Color3();
            this.toGammaSpaceToRef(convertedColor);
            return convertedColor;
        };
        /**
         * Converts the Color3 values to gamma space and stores the result in "convertedColor"
         * @param convertedColor defines the Color3 object where to store the gamma space version
         * @returns the unmodified Color3
         */
        Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
            convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
            convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
            convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
            return this;
        };
        // Statics
        /**
         * Creates a new Color3 from the string containing valid hexadecimal values
         * @param hex defines a string containing valid hexadecimal values
         * @returns a new Color3 object
         */
        Color3.FromHexString = function (hex) {
            if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
                return new Color3(0, 0, 0);
            }
            var r = parseInt(hex.substring(1, 3), 16);
            var g = parseInt(hex.substring(3, 5), 16);
            var b = parseInt(hex.substring(5, 7), 16);
            return Color3.FromInts(r, g, b);
        };
        /**
         * Creates a new Vector3 from the starting index of the given array
         * @param array defines the source array
         * @param offset defines an offset in the source array
         * @returns a new Color3 object
         */
        Color3.FromArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            return new Color3(array[offset], array[offset + 1], array[offset + 2]);
        };
        /**
         * Creates a new Color3 from integer values (< 256)
         * @param r defines the red component to read from (value between 0 and 255)
         * @param g defines the green component to read from (value between 0 and 255)
         * @param b defines the blue component to read from (value between 0 and 255)
         * @returns a new Color3 object
         */
        Color3.FromInts = function (r, g, b) {
            return new Color3(r / 255.0, g / 255.0, b / 255.0);
        };
        /**
         * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
         * @param start defines the start Color3 value
         * @param end defines the end Color3 value
         * @param amount defines the gradient value between start and end
         * @returns a new Color3 object
         */
        Color3.Lerp = function (start, end, amount) {
            var result = new Color3(0.0, 0.0, 0.0);
            Color3.LerpToRef(start, end, amount, result);
            return result;
        };
        /**
         * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
         * @param left defines the start value
         * @param right defines the end value
         * @param amount defines the gradient factor
         * @param result defines the Color3 object where to store the result
         */
        Color3.LerpToRef = function (left, right, amount, result) {
            result.r = left.r + ((right.r - left.r) * amount);
            result.g = left.g + ((right.g - left.g) * amount);
            result.b = left.b + ((right.b - left.b) * amount);
        };
        /**
         * Returns a Color3 value containing a red color
         * @returns a new Color3 object
         */
        Color3.Red = function () { return new Color3(1, 0, 0); };
        /**
         * Returns a Color3 value containing a green color
         * @returns a new Color3 object
         */
        Color3.Green = function () { return new Color3(0, 1, 0); };
        /**
         * Returns a Color3 value containing a blue color
         * @returns a new Color3 object
         */
        Color3.Blue = function () { return new Color3(0, 0, 1); };
        /**
         * Returns a Color3 value containing a black color
         * @returns a new Color3 object
         */
        Color3.Black = function () { return new Color3(0, 0, 0); };
        /**
         * Returns a Color3 value containing a white color
         * @returns a new Color3 object
         */
        Color3.White = function () { return new Color3(1, 1, 1); };
        /**
         * Returns a Color3 value containing a purple color
         * @returns a new Color3 object
         */
        Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
        /**
         * Returns a Color3 value containing a magenta color
         * @returns a new Color3 object
         */
        Color3.Magenta = function () { return new Color3(1, 0, 1); };
        /**
         * Returns a Color3 value containing a yellow color
         * @returns a new Color3 object
         */
        Color3.Yellow = function () { return new Color3(1, 1, 0); };
        /**
         * Returns a Color3 value containing a gray color
         * @returns a new Color3 object
         */
        Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
        /**
         * Returns a Color3 value containing a teal color
         * @returns a new Color3 object
         */
        Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
        /**
         * Returns a Color3 value containing a random color
         * @returns a new Color3 object
         */
        Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
        return Color3;
    }());
    BABYLON.Color3 = Color3;
    /**
     * Class used to hold a RBGA color
     */
    var Color4 = /** @class */ (function () {
        /**
         * Creates a new Color4 object from red, green, blue values, all between 0 and 1
         * @param r defines the red component (between 0 and 1, default is 0)
         * @param g defines the green component (between 0 and 1, default is 0)
         * @param b defines the blue component (between 0 and 1, default is 0)
         * @param a defines the alpha component (between 0 and 1, default is 1)
         */
        function Color4(
        /**
         * Defines the red component (between 0 and 1, default is 0)
         */
        r, 
        /**
         * Defines the green component (between 0 and 1, default is 0)
         */
        g, 
        /**
         * Defines the blue component (between 0 and 1, default is 0)
         */
        b, 
        /**
         * Defines the alpha component (between 0 and 1, default is 1)
         */
        a) {
            if (r === void 0) { r = 0; }
            if (g === void 0) { g = 0; }
            if (b === void 0) { b = 0; }
            if (a === void 0) { a = 1; }
            this.r = r;
            this.g = g;
            this.b = b;
            this.a = a;
        }
        // Operators
        /**
         * Adds in place the given Color4 values to the current Color4 object
         * @param right defines the second operand
         * @returns the current updated Color4 object
         */
        Color4.prototype.addInPlace = function (right) {
            this.r += right.r;
            this.g += right.g;
            this.b += right.b;
            this.a += right.a;
            return this;
        };
        /**
         * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
         * @returns the new array
         */
        Color4.prototype.asArray = function () {
            var result = new Array();
            this.toArray(result, 0);
            return result;
        };
        /**
         * Stores from the starting index in the given array the Color4 successive values
         * @param array defines the array where to store the r,g,b components
         * @param index defines an optional index in the target array to define where to start storing values
         * @returns the current Color4 object
         */
        Color4.prototype.toArray = function (array, index) {
            if (index === undefined) {
                index = 0;
            }
            array[index] = this.r;
            array[index + 1] = this.g;
            array[index + 2] = this.b;
            array[index + 3] = this.a;
            return this;
        };
        /**
         * Creates a new Color4 set with the added values of the current Color4 and of the given one
         * @param right defines the second operand
         * @returns a new Color4 object
         */
        Color4.prototype.add = function (right) {
            return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
        };
        /**
         * Creates a new Color4 set with the subtracted values of the given one from the current Color4
         * @param right defines the second operand
         * @returns a new Color4 object
         */
        Color4.prototype.subtract = function (right) {
            return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
        };
        /**
         * Subtracts the given ones from the current Color4 values and stores the results in "result"
         * @param right defines the second operand
         * @param result defines the Color4 object where to store the result
         * @returns the current Color4 object
         */
        Color4.prototype.subtractToRef = function (right, result) {
            result.r = this.r - right.r;
            result.g = this.g - right.g;
            result.b = this.b - right.b;
            result.a = this.a - right.a;
            return this;
        };
        /**
         * Creates a new Color4 with the current Color4 values multiplied by scale
         * @param scale defines the scaling factor to apply
         * @returns a new Color4 object
         */
        Color4.prototype.scale = function (scale) {
            return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
        };
        /**
         * Multiplies the current Color4 values by scale and stores the result in "result"
         * @param scale defines the scaling factor to apply
         * @param result defines the Color4 object where to store the result
         * @returns the current unmodified Color4
         */
        Color4.prototype.scaleToRef = function (scale, result) {
            result.r = this.r * scale;
            result.g = this.g * scale;
            result.b = this.b * scale;
            result.a = this.a * scale;
            return this;
        };
        /**
         * Scale the current Color4 values by a factor and add the result to a given Color4
         * @param scale defines the scale factor
         * @param result defines the Color4 object where to store the result
         * @returns the unmodified current Color4
         */
        Color4.prototype.scaleAndAddToRef = function (scale, result) {
            result.r += this.r * scale;
            result.g += this.g * scale;
            result.b += this.b * scale;
            result.a += this.a * scale;
            return this;
        };
        /**
         * Clamps the rgb values by the min and max values and stores the result into "result"
         * @param min defines minimum clamping value (default is 0)
         * @param max defines maximum clamping value (default is 1)
         * @param result defines color to store the result into.
         * @returns the cuurent Color4
         */
        Color4.prototype.clampToRef = function (min, max, result) {
            if (min === void 0) { min = 0; }
            if (max === void 0) { max = 1; }
            result.r = BABYLON.Scalar.Clamp(this.r, min, max);
            result.g = BABYLON.Scalar.Clamp(this.g, min, max);
            result.b = BABYLON.Scalar.Clamp(this.b, min, max);
            result.a = BABYLON.Scalar.Clamp(this.a, min, max);
            return this;
        };
        /**
          * Multipy an Color4 value by another and return a new Color4 object
          * @param color defines the Color4 value to multiply by
          * @returns a new Color4 object
          */
        Color4.prototype.multiply = function (color) {
            return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
        };
        /**
         * Multipy a Color4 value by another and push the result in a reference value
         * @param color defines the Color4 value to multiply by
         * @param result defines the Color4 to fill the result in
         * @returns the result Color4
         */
        Color4.prototype.multiplyToRef = function (color, result) {
            result.r = this.r * color.r;
            result.g = this.g * color.g;
            result.b = this.b * color.b;
            result.a = this.a * color.a;
            return result;
        };
        /**
         * Creates a string with the Color4 current values
         * @returns the string representation of the Color4 object
         */
        Color4.prototype.toString = function () {
            return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
        };
        /**
         * Returns the string "Color4"
         * @returns "Color4"
         */
        Color4.prototype.getClassName = function () {
            return "Color4";
        };
        /**
         * Compute the Color4 hash code
         * @returns an unique number that can be used to hash Color4 objects
         */
        Color4.prototype.getHashCode = function () {
            var hash = this.r || 0;
            hash = (hash * 397) ^ (this.g || 0);
            hash = (hash * 397) ^ (this.b || 0);
            hash = (hash * 397) ^ (this.a || 0);
            return hash;
        };
        /**
         * Creates a new Color4 copied from the current one
         * @returns a new Color4 object
         */
        Color4.prototype.clone = function () {
            return new Color4(this.r, this.g, this.b, this.a);
        };
        /**
         * Copies the given Color4 values into the current one
         * @param source defines the source Color4 object
         * @returns the current updated Color4 object
         */
        Color4.prototype.copyFrom = function (source) {
            this.r = source.r;
            this.g = source.g;
            this.b = source.b;
            this.a = source.a;
            return this;
        };
        /**
         * Copies the given float values into the current one
         * @param r defines the red component to read from
         * @param g defines the green component to read from
         * @param b defines the blue component to read from
         * @param a defines the alpha component to read from
         * @returns the current updated Color4 object
         */
        Color4.prototype.copyFromFloats = function (r, g, b, a) {
            this.r = r;
            this.g = g;
            this.b = b;
            this.a = a;
            return this;
        };
        /**
         * Copies the given float values into the current one
         * @param r defines the red component to read from
         * @param g defines the green component to read from
         * @param b defines the blue component to read from
         * @param a defines the alpha component to read from
         * @returns the current updated Color4 object
         */
        Color4.prototype.set = function (r, g, b, a) {
            return this.copyFromFloats(r, g, b, a);
        };
        /**
         * Compute the Color4 hexadecimal code as a string
         * @returns a string containing the hexadecimal representation of the Color4 object
         */
        Color4.prototype.toHexString = function () {
            var intR = (this.r * 255) | 0;
            var intG = (this.g * 255) | 0;
            var intB = (this.b * 255) | 0;
            var intA = (this.a * 255) | 0;
            return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
        };
        /**
         * Computes a new Color4 converted from the current one to linear space
         * @returns a new Color4 object
         */
        Color4.prototype.toLinearSpace = function () {
            var convertedColor = new Color4();
            this.toLinearSpaceToRef(convertedColor);
            return convertedColor;
        };
        /**
         * Converts the Color4 values to linear space and stores the result in "convertedColor"
         * @param convertedColor defines the Color4 object where to store the linear space version
         * @returns the unmodified Color4
         */
        Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
            convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
            convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
            convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
            convertedColor.a = this.a;
            return this;
        };
        /**
         * Computes a new Color4 converted from the current one to gamma space
         * @returns a new Color4 object
         */
        Color4.prototype.toGammaSpace = function () {
            var convertedColor = new Color4();
            this.toGammaSpaceToRef(convertedColor);
            return convertedColor;
        };
        /**
         * Converts the Color4 values to gamma space and stores the result in "convertedColor"
         * @param convertedColor defines the Color4 object where to store the gamma space version
         * @returns the unmodified Color4
         */
        Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
            convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
            convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
            convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
            convertedColor.a = this.a;
            return this;
        };
        // Statics
        /**
         * Creates a new Color4 from the string containing valid hexadecimal values
         * @param hex defines a string containing valid hexadecimal values
         * @returns a new Color4 object
         */
        Color4.FromHexString = function (hex) {
            if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
                return new Color4(0.0, 0.0, 0.0, 0.0);
            }
            var r = parseInt(hex.substring(1, 3), 16);
            var g = parseInt(hex.substring(3, 5), 16);
            var b = parseInt(hex.substring(5, 7), 16);
            var a = parseInt(hex.substring(7, 9), 16);
            return Color4.FromInts(r, g, b, a);
        };
        /**
         * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
         * @param left defines the start value
         * @param right defines the end value
         * @param amount defines the gradient factor
         * @returns a new Color4 object
         */
        Color4.Lerp = function (left, right, amount) {
            var result = new Color4(0.0, 0.0, 0.0, 0.0);
            Color4.LerpToRef(left, right, amount, result);
            return result;
        };
        /**
         * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
         * @param left defines the start value
         * @param right defines the end value
         * @param amount defines the gradient factor
         * @param result defines the Color4 object where to store data
         */
        Color4.LerpToRef = function (left, right, amount, result) {
            result.r = left.r + (right.r - left.r) * amount;
            result.g = left.g + (right.g - left.g) * amount;
            result.b = left.b + (right.b - left.b) * amount;
            result.a = left.a + (right.a - left.a) * amount;
        };
        /**
         * Creates a new Color4 from a Color3 and an alpha value
         * @param color3 defines the source Color3 to read from
         * @param alpha defines the alpha component (1.0 by default)
         * @returns a new Color4 object
         */
        Color4.FromColor3 = function (color3, alpha) {
            if (alpha === void 0) { alpha = 1.0; }
            return new Color4(color3.r, color3.g, color3.b, alpha);
        };
        /**
         * Creates a new Color4 from the starting index element of the given array
         * @param array defines the source array to read from
         * @param offset defines the offset in the source array
         * @returns a new Color4 object
         */
        Color4.FromArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
        };
        /**
         * Creates a new Color3 from integer values (< 256)
         * @param r defines the red component to read from (value between 0 and 255)
         * @param g defines the green component to read from (value between 0 and 255)
         * @param b defines the blue component to read from (value between 0 and 255)
         * @param a defines the alpha component to read from (value between 0 and 255)
         * @returns a new Color3 object
         */
        Color4.FromInts = function (r, g, b, a) {
            return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
        };
        /**
         * Check the content of a given array and convert it to an array containing RGBA data
         * If the original array was already containing count * 4 values then it is returned directly
         * @param colors defines the array to check
         * @param count defines the number of RGBA data to expect
         * @returns an array containing count * 4 values (RGBA)
         */
        Color4.CheckColors4 = function (colors, count) {
            // Check if color3 was used
            if (colors.length === count * 3) {
                var colors4 = [];
                for (var index = 0; index < colors.length; index += 3) {
                    var newIndex = (index / 3) * 4;
                    colors4[newIndex] = colors[index];
                    colors4[newIndex + 1] = colors[index + 1];
                    colors4[newIndex + 2] = colors[index + 2];
                    colors4[newIndex + 3] = 1.0;
                }
                return colors4;
            }
            return colors;
        };
        return Color4;
    }());
    BABYLON.Color4 = Color4;
    /**
     * Class representing a vector containing 2 coordinates
     */
    var Vector2 = /** @class */ (function () {
        /**
         * Creates a new Vector2 from the given x and y coordinates
         * @param x defines the first coordinate
         * @param y defines the second coordinate
         */
        function Vector2(
        /** defines the first coordinate */
        x, 
        /** defines the second coordinate */
        y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            this.x = x;
            this.y = y;
        }
        /**
         * Gets a string with the Vector2 coordinates
         * @returns a string with the Vector2 coordinates
         */
        Vector2.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + "}";
        };
        /**
         * Gets class name
         * @returns the string "Vector2"
         */
        Vector2.prototype.getClassName = function () {
            return "Vector2";
        };
        /**
         * Gets current vector hash code
         * @returns the Vector2 hash code as a number
         */
        Vector2.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            return hash;
        };
        // Operators
        /**
         * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
         * @param array defines the source array
         * @param index defines the offset in source array
         * @returns the current Vector2
         */
        Vector2.prototype.toArray = function (array, index) {
            if (index === void 0) { index = 0; }
            array[index] = this.x;
            array[index + 1] = this.y;
            return this;
        };
        /**
         * Copy the current vector to an array
         * @returns a new array with 2 elements: the Vector2 coordinates.
         */
        Vector2.prototype.asArray = function () {
            var result = new Array();
            this.toArray(result, 0);
            return result;
        };
        /**
         * Sets the Vector2 coordinates with the given Vector2 coordinates
         * @param source defines the source Vector2
         * @returns the current updated Vector2
         */
        Vector2.prototype.copyFrom = function (source) {
            this.x = source.x;
            this.y = source.y;
            return this;
        };
        /**
         * Sets the Vector2 coordinates with the given floats
         * @param x defines the first coordinate
         * @param y defines the second coordinate
         * @returns the current updated Vector2
         */
        Vector2.prototype.copyFromFloats = function (x, y) {
            this.x = x;
            this.y = y;
            return this;
        };
        /**
         * Sets the Vector2 coordinates with the given floats
         * @param x defines the first coordinate
         * @param y defines the second coordinate
         * @returns the current updated Vector2
         */
        Vector2.prototype.set = function (x, y) {
            return this.copyFromFloats(x, y);
        };
        /**
         * Add another vector with the current one
         * @param otherVector defines the other vector
         * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
         */
        Vector2.prototype.add = function (otherVector) {
            return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
        };
        /**
         * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
         * @param otherVector defines the other vector
         * @param result defines the target vector
         * @returns the unmodified current Vector2
         */
        Vector2.prototype.addToRef = function (otherVector, result) {
            result.x = this.x + otherVector.x;
            result.y = this.y + otherVector.y;
            return this;
        };
        /**
         * Set the Vector2 coordinates by adding the given Vector2 coordinates
         * @param otherVector defines the other vector
         * @returns the current updated Vector2
         */
        Vector2.prototype.addInPlace = function (otherVector) {
            this.x += otherVector.x;
            this.y += otherVector.y;
            return this;
        };
        /**
         * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
         * @param otherVector defines the other vector
         * @returns a new Vector2
         */
        Vector2.prototype.addVector3 = function (otherVector) {
            return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
        };
        /**
         * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
         * @param otherVector defines the other vector
         * @returns a new Vector2
         */
        Vector2.prototype.subtract = function (otherVector) {
            return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
        };
        /**
         * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
         * @param otherVector defines the other vector
         * @param result defines the target vector
         * @returns the unmodified current Vector2
         */
        Vector2.prototype.subtractToRef = function (otherVector, result) {
            result.x = this.x - otherVector.x;
            result.y = this.y - otherVector.y;
            return this;
        };
        /**
         * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
         * @param otherVector defines the other vector
         * @returns the current updated Vector2
         */
        Vector2.prototype.subtractInPlace = function (otherVector) {
            this.x -= otherVector.x;
            this.y -= otherVector.y;
            return this;
        };
        /**
         * Multiplies in place the current Vector2 coordinates by the given ones
         * @param otherVector defines the other vector
         * @returns the current updated Vector2
         */
        Vector2.prototype.multiplyInPlace = function (otherVector) {
            this.x *= otherVector.x;
            this.y *= otherVector.y;
            return this;
        };
        /**
         * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
         * @param otherVector defines the other vector
         * @returns a new Vector2
         */
        Vector2.prototype.multiply = function (otherVector) {
            return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
        };
        /**
         * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
         * @param otherVector defines the other vector
         * @param result defines the target vector
         * @returns the unmodified current Vector2
         */
        Vector2.prototype.multiplyToRef = function (otherVector, result) {
            result.x = this.x * otherVector.x;
            result.y = this.y * otherVector.y;
            return this;
        };
        /**
         * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
         * @param x defines the first coordinate
         * @param y defines the second coordinate
         * @returns a new Vector2
         */
        Vector2.prototype.multiplyByFloats = function (x, y) {
            return new Vector2(this.x * x, this.y * y);
        };
        /**
         * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
         * @param otherVector defines the other vector
         * @returns a new Vector2
         */
        Vector2.prototype.divide = function (otherVector) {
            return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
        };
        /**
         * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
         * @param otherVector defines the other vector
         * @param result defines the target vector
         * @returns the unmodified current Vector2
         */
        Vector2.prototype.divideToRef = function (otherVector, result) {
            result.x = this.x / otherVector.x;
            result.y = this.y / otherVector.y;
            return this;
        };
        /**
         * Divides the current Vector2 coordinates by the given ones
         * @param otherVector defines the other vector
         * @returns the current updated Vector2
         */
        Vector2.prototype.divideInPlace = function (otherVector) {
            return this.divideToRef(otherVector, this);
        };
        /**
         * Gets a new Vector2 with current Vector2 negated coordinates
         * @returns a new Vector2
         */
        Vector2.prototype.negate = function () {
            return new Vector2(-this.x, -this.y);
        };
        /**
         * Multiply the Vector2 coordinates by scale
         * @param scale defines the scaling factor
         * @returns the current updated Vector2
         */
        Vector2.prototype.scaleInPlace = function (scale) {
            this.x *= scale;
            this.y *= scale;
            return this;
        };
        /**
         * Returns a new Vector2 scaled by "scale" from the current Vector2
         * @param scale defines the scaling factor
         * @returns a new Vector2
         */
        Vector2.prototype.scale = function (scale) {
            var result = new Vector2(0, 0);
            this.scaleToRef(scale, result);
            return result;
        };
        /**
         * Scale the current Vector2 values by a factor to a given Vector2
         * @param scale defines the scale factor
         * @param result defines the Vector2 object where to store the result
         * @returns the unmodified current Vector2
         */
        Vector2.prototype.scaleToRef = function (scale, result) {
            result.x = this.x * scale;
            result.y = this.y * scale;
            return this;
        };
        /**
         * Scale the current Vector2 values by a factor and add the result to a given Vector2
         * @param scale defines the scale factor
         * @param result defines the Vector2 object where to store the result
         * @returns the unmodified current Vector2
         */
        Vector2.prototype.scaleAndAddToRef = function (scale, result) {
            result.x += this.x * scale;
            result.y += this.y * scale;
            return this;
        };
        /**
         * Gets a boolean if two vectors are equals
         * @param otherVector defines the other vector
         * @returns true if the given vector coordinates strictly equal the current Vector2 ones
         */
        Vector2.prototype.equals = function (otherVector) {
            return otherVector && this.x === otherVector.x && this.y === otherVector.y;
        };
        /**
         * Gets a boolean if two vectors are equals (using an epsilon value)
         * @param otherVector defines the other vector
         * @param epsilon defines the minimal distance to consider equality
         * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
         */
        Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
            if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
            return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
        };
        /**
         * Gets a new Vector2 from current Vector2 floored values
         * @returns a new Vector2
         */
        Vector2.prototype.floor = function () {
            return new Vector2(Math.floor(this.x), Math.floor(this.y));
        };
        /**
         * Gets a new Vector2 from current Vector2 floored values
         * @returns a new Vector2
         */
        Vector2.prototype.fract = function () {
            return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
        };
        // Properties
        /**
         * Gets the length of the vector
         * @returns the vector length (float)
         */
        Vector2.prototype.length = function () {
            return Math.sqrt(this.x * this.x + this.y * this.y);
        };
        /**
         * Gets the vector squared length
         * @returns the vector squared length (float)
         */
        Vector2.prototype.lengthSquared = function () {
            return (this.x * this.x + this.y * this.y);
        };
        // Methods
        /**
         * Normalize the vector
         * @returns the current updated Vector2
         */
        Vector2.prototype.normalize = function () {
            var len = this.length();
            if (len === 0) {
                return this;
            }
            var num = 1.0 / len;
            this.x *= num;
            this.y *= num;
            return this;
        };
        /**
         * Gets a new Vector2 copied from the Vector2
         * @returns a new Vector2
         */
        Vector2.prototype.clone = function () {
            return new Vector2(this.x, this.y);
        };
        // Statics
        /**
         * Gets a new Vector2(0, 0)
         * @returns a new Vector2
         */
        Vector2.Zero = function () {
            return new Vector2(0, 0);
        };
        /**
         * Gets a new Vector2(1, 1)
         * @returns a new Vector2
         */
        Vector2.One = function () {
            return new Vector2(1, 1);
        };
        /**
         * Gets a new Vector2 set from the given index element of the given array
         * @param array defines the data source
         * @param offset defines the offset in the data source
         * @returns a new Vector2
         */
        Vector2.FromArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            return new Vector2(array[offset], array[offset + 1]);
        };
        /**
         * Sets "result" from the given index element of the given array
         * @param array defines the data source
         * @param offset defines the offset in the data source
         * @param result defines the target vector
         */
        Vector2.FromArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
        };
        /**
         * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
         * @param value1 defines 1st point of control
         * @param value2 defines 2nd point of control
         * @param value3 defines 3rd point of control
         * @param value4 defines 4th point of control
         * @param amount defines the interpolation factor
         * @returns a new Vector2
         */
        Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
                (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
                ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
            var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
                (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
                ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
            return new Vector2(x, y);
        };
        /**
         * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
         * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
         * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
         * @param value defines the value to clamp
         * @param min defines the lower limit
         * @param max defines the upper limit
         * @returns a new Vector2
         */
        Vector2.Clamp = function (value, min, max) {
            var x = value.x;
            x = (x > max.x) ? max.x : x;
            x = (x < min.x) ? min.x : x;
            var y = value.y;
            y = (y > max.y) ? max.y : y;
            y = (y < min.y) ? min.y : y;
            return new Vector2(x, y);
        };
        /**
         * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
         * @param value1 defines the 1st control point
         * @param tangent1 defines the outgoing tangent
         * @param value2 defines the 2nd control point
         * @param tangent2 defines the incoming tangent
         * @param amount defines the interpolation factor
         * @returns a new Vector2
         */
        Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
            var part2 = (-2.0 * cubed) + (3.0 * squared);
            var part3 = (cubed - (2.0 * squared)) + amount;
            var part4 = cubed - squared;
            var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
            var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
            return new Vector2(x, y);
        };
        /**
         * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
         * @param start defines the start vector
         * @param end defines the end vector
         * @param amount defines the interpolation factor
         * @returns a new Vector2
         */
        Vector2.Lerp = function (start, end, amount) {
            var x = start.x + ((end.x - start.x) * amount);
            var y = start.y + ((end.y - start.y) * amount);
            return new Vector2(x, y);
        };
        /**
         * Gets the dot product of the vector "left" and the vector "right"
         * @param left defines first vector
         * @param right defines second vector
         * @returns the dot product (float)
         */
        Vector2.Dot = function (left, right) {
            return left.x * right.x + left.y * right.y;
        };
        /**
         * Returns a new Vector2 equal to the normalized given vector
         * @param vector defines the vector to normalize
         * @returns a new Vector2
         */
        Vector2.Normalize = function (vector) {
            var newVector = vector.clone();
            newVector.normalize();
            return newVector;
        };
        /**
         * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
         * @param left defines 1st vector
         * @param right defines 2nd vector
         * @returns a new Vector2
         */
        Vector2.Minimize = function (left, right) {
            var x = (left.x < right.x) ? left.x : right.x;
            var y = (left.y < right.y) ? left.y : right.y;
            return new Vector2(x, y);
        };
        /**
         * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
         * @param left defines 1st vector
         * @param right defines 2nd vector
         * @returns a new Vector2
         */
        Vector2.Maximize = function (left, right) {
            var x = (left.x > right.x) ? left.x : right.x;
            var y = (left.y > right.y) ? left.y : right.y;
            return new Vector2(x, y);
        };
        /**
         * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
         * @param vector defines the vector to transform
         * @param transformation defines the matrix to apply
         * @returns a new Vector2
         */
        Vector2.Transform = function (vector, transformation) {
            var r = Vector2.Zero();
            Vector2.TransformToRef(vector, transformation, r);
            return r;
        };
        /**
         * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
         * @param vector defines the vector to transform
         * @param transformation defines the matrix to apply
         * @param result defines the target vector
         */
        Vector2.TransformToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
            result.x = x;
            result.y = y;
        };
        /**
         * Determines if a given vector is included in a triangle
         * @param p defines the vector to test
         * @param p0 defines 1st triangle point
         * @param p1 defines 2nd triangle point
         * @param p2 defines 3rd triangle point
         * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
         */
        Vector2.PointInTriangle = function (p, p0, p1, p2) {
            var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
            var sign = a < 0 ? -1 : 1;
            var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
            var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
            return s > 0 && t > 0 && (s + t) < 2 * a * sign;
        };
        /**
         * Gets the distance between the vectors "value1" and "value2"
         * @param value1 defines first vector
         * @param value2 defines second vector
         * @returns the distance between vectors
         */
        Vector2.Distance = function (value1, value2) {
            return Math.sqrt(Vector2.DistanceSquared(value1, value2));
        };
        /**
         * Returns the squared distance between the vectors "value1" and "value2"
         * @param value1 defines first vector
         * @param value2 defines second vector
         * @returns the squared distance between vectors
         */
        Vector2.DistanceSquared = function (value1, value2) {
            var x = value1.x - value2.x;
            var y = value1.y - value2.y;
            return (x * x) + (y * y);
        };
        /**
         * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
         * @param value1 defines first vector
         * @param value2 defines second vector
         * @returns a new Vector2
         */
        Vector2.Center = function (value1, value2) {
            var center = value1.add(value2);
            center.scaleInPlace(0.5);
            return center;
        };
        /**
         * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
         * @param p defines the middle point
         * @param segA defines one point of the segment
         * @param segB defines the other point of the segment
         * @returns the shortest distance
         */
        Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
            var l2 = Vector2.DistanceSquared(segA, segB);
            if (l2 === 0.0) {
                return Vector2.Distance(p, segA);
            }
            var v = segB.subtract(segA);
            var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
            var proj = segA.add(v.multiplyByFloats(t, t));
            return Vector2.Distance(p, proj);
        };
        return Vector2;
    }());
    BABYLON.Vector2 = Vector2;
    /**
     * Classed used to store (x,y,z) vector representation
     * A Vector3 is the main object used in 3D geometry
     * It can represent etiher the coordinates of a point the space, either a direction
     * Reminder: Babylon.js uses a left handed forward facing system
     */
    var Vector3 = /** @class */ (function () {
        /**
         * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
         * @param x defines the first coordinates (on X axis)
         * @param y defines the second coordinates (on Y axis)
         * @param z defines the third coordinates (on Z axis)
         */
        function Vector3(
        /**
         * Defines the first coordinates (on X axis)
         */
        x, 
        /**
         * Defines the second coordinates (on Y axis)
         */
        y, 
        /**
         * Defines the third coordinates (on Z axis)
         */
        z) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            if (z === void 0) { z = 0; }
            this.x = x;
            this.y = y;
            this.z = z;
        }
        /**
         * Creates a string representation of the Vector3
         * @returns a string with the Vector3 coordinates.
         */
        Vector3.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
        };
        /**
         * Gets the class name
         * @returns the string "Vector3"
         */
        Vector3.prototype.getClassName = function () {
            return "Vector3";
        };
        /**
         * Creates the Vector3 hash code
         * @returns a number which tends to be unique between Vector3 instances
         */
        Vector3.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            hash = (hash * 397) ^ (this.z || 0);
            return hash;
        };
        // Operators
        /**
         * Creates an array containing three elements : the coordinates of the Vector3
         * @returns a new array of numbers
         */
        Vector3.prototype.asArray = function () {
            var result = [];
            this.toArray(result, 0);
            return result;
        };
        /**
         * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
         * @param array defines the destination array
         * @param index defines the offset in the destination array
         * @returns the current Vector3
         */
        Vector3.prototype.toArray = function (array, index) {
            if (index === void 0) { index = 0; }
            array[index] = this.x;
            array[index + 1] = this.y;
            array[index + 2] = this.z;
            return this;
        };
        /**
         * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
         * @returns a new Quaternion object, computed from the Vector3 coordinates
         */
        Vector3.prototype.toQuaternion = function () {
            return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
        };
        /**
         * Adds the given vector to the current Vector3
         * @param otherVector defines the second operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.addInPlace = function (otherVector) {
            this.x += otherVector.x;
            this.y += otherVector.y;
            this.z += otherVector.z;
            return this;
        };
        /**
         * Gets a new Vector3, result of the addition the current Vector3 and the given vector
         * @param otherVector defines the second operand
         * @returns the resulting Vector3
         */
        Vector3.prototype.add = function (otherVector) {
            return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
        };
        /**
         * Adds the current Vector3 to the given one and stores the result in the vector "result"
         * @param otherVector defines the second operand
         * @param result defines the Vector3 object where to store the result
         * @returns the current Vector3
         */
        Vector3.prototype.addToRef = function (otherVector, result) {
            result.x = this.x + otherVector.x;
            result.y = this.y + otherVector.y;
            result.z = this.z + otherVector.z;
            return this;
        };
        /**
         * Subtract the given vector from the current Vector3
         * @param otherVector defines the second operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.subtractInPlace = function (otherVector) {
            this.x -= otherVector.x;
            this.y -= otherVector.y;
            this.z -= otherVector.z;
            return this;
        };
        /**
         * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
         * @param otherVector defines the second operand
         * @returns the resulting Vector3
         */
        Vector3.prototype.subtract = function (otherVector) {
            return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
        };
        /**
         * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
         * @param otherVector defines the second operand
         * @param result defines the Vector3 object where to store the result
         * @returns the current Vector3
         */
        Vector3.prototype.subtractToRef = function (otherVector, result) {
            result.x = this.x - otherVector.x;
            result.y = this.y - otherVector.y;
            result.z = this.z - otherVector.z;
            return this;
        };
        /**
         * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns the resulting Vector3
         */
        Vector3.prototype.subtractFromFloats = function (x, y, z) {
            return new Vector3(this.x - x, this.y - y, this.z - z);
        };
        /**
         * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @param result defines the Vector3 object where to store the result
         * @returns the current Vector3
         */
        Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
            result.x = this.x - x;
            result.y = this.y - y;
            result.z = this.z - z;
            return this;
        };
        /**
         * Gets a new Vector3 set with the current Vector3 negated coordinates
         * @returns a new Vector3
         */
        Vector3.prototype.negate = function () {
            return new Vector3(-this.x, -this.y, -this.z);
        };
        /**
         * Multiplies the Vector3 coordinates by the float "scale"
         * @param scale defines the multiplier factor
         * @returns the current updated Vector3
         */
        Vector3.prototype.scaleInPlace = function (scale) {
            this.x *= scale;
            this.y *= scale;
            this.z *= scale;
            return this;
        };
        /**
         * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
         * @param scale defines the multiplier factor
         * @returns a new Vector3
         */
        Vector3.prototype.scale = function (scale) {
            return new Vector3(this.x * scale, this.y * scale, this.z * scale);
        };
        /**
         * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
         * @param scale defines the multiplier factor
         * @param result defines the Vector3 object where to store the result
         * @returns the current Vector3
         */
        Vector3.prototype.scaleToRef = function (scale, result) {
            result.x = this.x * scale;
            result.y = this.y * scale;
            result.z = this.z * scale;
            return this;
        };
        /**
         * Scale the current Vector3 values by a factor and add the result to a given Vector3
         * @param scale defines the scale factor
         * @param result defines the Vector3 object where to store the result
         * @returns the unmodified current Vector3
         */
        Vector3.prototype.scaleAndAddToRef = function (scale, result) {
            result.x += this.x * scale;
            result.y += this.y * scale;
            result.z += this.z * scale;
            return this;
        };
        /**
         * Returns true if the current Vector3 and the given vector coordinates are strictly equal
         * @param otherVector defines the second operand
         * @returns true if both vectors are equals
         */
        Vector3.prototype.equals = function (otherVector) {
            return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
        };
        /**
         * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
         * @param otherVector defines the second operand
         * @param epsilon defines the minimal distance to define values as equals
         * @returns true if both vectors are distant less than epsilon
         */
        Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
            if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
            return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
        };
        /**
         * Returns true if the current Vector3 coordinates equals the given floats
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns true if both vectors are equals
         */
        Vector3.prototype.equalsToFloats = function (x, y, z) {
            return this.x === x && this.y === y && this.z === z;
        };
        /**
         * Multiplies the current Vector3 coordinates by the given ones
         * @param otherVector defines the second operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.multiplyInPlace = function (otherVector) {
            this.x *= otherVector.x;
            this.y *= otherVector.y;
            this.z *= otherVector.z;
            return this;
        };
        /**
         * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
         * @param otherVector defines the second operand
         * @returns the new Vector3
         */
        Vector3.prototype.multiply = function (otherVector) {
            return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
        };
        /**
         * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
         * @param otherVector defines the second operand
         * @param result defines the Vector3 object where to store the result
         * @returns the current Vector3
         */
        Vector3.prototype.multiplyToRef = function (otherVector, result) {
            result.x = this.x * otherVector.x;
            result.y = this.y * otherVector.y;
            result.z = this.z * otherVector.z;
            return this;
        };
        /**
         * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns the new Vector3
         */
        Vector3.prototype.multiplyByFloats = function (x, y, z) {
            return new Vector3(this.x * x, this.y * y, this.z * z);
        };
        /**
         * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
         * @param otherVector defines the second operand
         * @returns the new Vector3
         */
        Vector3.prototype.divide = function (otherVector) {
            return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
        };
        /**
         * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
         * @param otherVector defines the second operand
         * @param result defines the Vector3 object where to store the result
         * @returns the current Vector3
         */
        Vector3.prototype.divideToRef = function (otherVector, result) {
            result.x = this.x / otherVector.x;
            result.y = this.y / otherVector.y;
            result.z = this.z / otherVector.z;
            return this;
        };
        /**
         * Divides the current Vector3 coordinates by the given ones.
         * @param otherVector defines the second operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.divideInPlace = function (otherVector) {
            return this.divideToRef(otherVector, this);
        };
        /**
         * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
         * @param other defines the second operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.minimizeInPlace = function (other) {
            return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
        };
        /**
         * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
         * @param other defines the second operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.maximizeInPlace = function (other) {
            return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
        };
        /**
         * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
            if (x < this.x) {
                this.x = x;
            }
            if (y < this.y) {
                this.y = y;
            }
            if (z < this.z) {
                this.z = z;
            }
            return this;
        };
        /**
         * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
            if (x > this.x) {
                this.x = x;
            }
            if (y > this.y) {
                this.y = y;
            }
            if (z > this.z) {
                this.z = z;
            }
            return this;
        };
        Object.defineProperty(Vector3.prototype, "isNonUniform", {
            /**
             * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
             */
            get: function () {
                var absX = Math.abs(this.x);
                var absY = Math.abs(this.y);
                if (absX !== absY) {
                    return true;
                }
                var absZ = Math.abs(this.z);
                if (absX !== absZ) {
                    return true;
                }
                if (absY !== absZ) {
                    return true;
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets a new Vector3 from current Vector3 floored values
         * @returns a new Vector3
         */
        Vector3.prototype.floor = function () {
            return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
        };
        /**
         * Gets a new Vector3 from current Vector3 floored values
         * @returns a new Vector3
         */
        Vector3.prototype.fract = function () {
            return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
        };
        // Properties
        /**
         * Gets the length of the Vector3
         * @returns the length of the Vecto3
         */
        Vector3.prototype.length = function () {
            return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
        };
        /**
         * Gets the squared length of the Vector3
         * @returns squared length of the Vector3
         */
        Vector3.prototype.lengthSquared = function () {
            return (this.x * this.x + this.y * this.y + this.z * this.z);
        };
        /**
         * Normalize the current Vector3.
         * Please note that this is an in place operation.
         * @returns the current updated Vector3
         */
        Vector3.prototype.normalize = function () {
            var len = this.length();
            if (len === 0 || len === 1.0) {
                return this;
            }
            var num = 1.0 / len;
            this.x *= num;
            this.y *= num;
            this.z *= num;
            return this;
        };
        /**
         * Normalize the current Vector3 to a new vector
         * @returns the new Vector3
         */
        Vector3.prototype.normalizeToNew = function () {
            var normalized = new Vector3(0, 0, 0);
            this.normalizeToRef(normalized);
            return normalized;
        };
        /**
         * Normalize the current Vector3 to the reference
         * @param reference define the Vector3 to update
         * @returns the updated Vector3
         */
        Vector3.prototype.normalizeToRef = function (reference) {
            var len = this.length();
            if (len === 0 || len === 1.0) {
                reference.set(this.x, this.y, this.z);
                return reference;
            }
            var scale = 1.0 / len;
            this.scaleToRef(scale, reference);
            return reference;
        };
        /**
         * Creates a new Vector3 copied from the current Vector3
         * @returns the new Vector3
         */
        Vector3.prototype.clone = function () {
            return new Vector3(this.x, this.y, this.z);
        };
        /**
         * Copies the given vector coordinates to the current Vector3 ones
         * @param source defines the source Vector3
         * @returns the current updated Vector3
         */
        Vector3.prototype.copyFrom = function (source) {
            this.x = source.x;
            this.y = source.y;
            this.z = source.z;
            return this;
        };
        /**
         * Copies the given floats to the current Vector3 coordinates
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.copyFromFloats = function (x, y, z) {
            this.x = x;
            this.y = y;
            this.z = z;
            return this;
        };
        /**
         * Copies the given floats to the current Vector3 coordinates
         * @param x defines the x coordinate of the operand
         * @param y defines the y coordinate of the operand
         * @param z defines the z coordinate of the operand
         * @returns the current updated Vector3
         */
        Vector3.prototype.set = function (x, y, z) {
            return this.copyFromFloats(x, y, z);
        };
        // Statics
        /**
         * Get the clip factor between two vectors
         * @param vector0 defines the first operand
         * @param vector1 defines the second operand
         * @param axis defines the axis to use
         * @param size defines the size along the axis
         * @returns the clip factor
         */
        Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
            var d0 = Vector3.Dot(vector0, axis) - size;
            var d1 = Vector3.Dot(vector1, axis) - size;
            var s = d0 / (d0 - d1);
            return s;
        };
        /**
         * Get angle between two vectors
         * @param vector0 angle between vector0 and vector1
         * @param vector1 angle between vector0 and vector1
         * @param normal direction of the normal
         * @return the angle between vector0 and vector1
         */
        Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
            var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
            var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
            var dot = Vector3.Dot(v0, v1);
            var n = MathTmp.Vector3[3];
            Vector3.CrossToRef(v0, v1, n);
            if (Vector3.Dot(n, normal) > 0) {
                return Math.acos(dot);
            }
            return -Math.acos(dot);
        };
        /**
         * Returns a new Vector3 set from the index "offset" of the given array
         * @param array defines the source array
         * @param offset defines the offset in the source array
         * @returns the new Vector3
         */
        Vector3.FromArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
        };
        /**
         * Returns a new Vector3 set from the index "offset" of the given Float32Array
         * This function is deprecated.  Use FromArray instead
         * @param array defines the source array
         * @param offset defines the offset in the source array
         * @returns the new Vector3
         */
        Vector3.FromFloatArray = function (array, offset) {
            return Vector3.FromArray(array, offset);
        };
        /**
         * Sets the given vector "result" with the element values from the index "offset" of the given array
         * @param array defines the source array
         * @param offset defines the offset in the source array
         * @param result defines the Vector3 where to store the result
         */
        Vector3.FromArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
            result.z = array[offset + 2];
        };
        /**
         * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
         * This function is deprecated.  Use FromArrayToRef instead.
         * @param array defines the source array
         * @param offset defines the offset in the source array
         * @param result defines the Vector3 where to store the result
         */
        Vector3.FromFloatArrayToRef = function (array, offset, result) {
            return Vector3.FromArrayToRef(array, offset, result);
        };
        /**
         * Sets the given vector "result" with the given floats.
         * @param x defines the x coordinate of the source
         * @param y defines the y coordinate of the source
         * @param z defines the z coordinate of the source
         * @param result defines the Vector3 where to store the result
         */
        Vector3.FromFloatsToRef = function (x, y, z, result) {
            result.x = x;
            result.y = y;
            result.z = z;
        };
        /**
         * Returns a new Vector3 set to (0.0, 0.0, 0.0)
         * @returns a new empty Vector3
         */
        Vector3.Zero = function () {
            return new Vector3(0.0, 0.0, 0.0);
        };
        /**
         * Returns a new Vector3 set to (1.0, 1.0, 1.0)
         * @returns a new unit Vector3
         */
        Vector3.One = function () {
            return new Vector3(1.0, 1.0, 1.0);
        };
        /**
         * Returns a new Vector3 set to (0.0, 1.0, 0.0)
         * @returns a new up Vector3
         */
        Vector3.Up = function () {
            return new Vector3(0.0, 1.0, 0.0);
        };
        /**
         * Returns a new Vector3 set to (0.0, -1.0, 0.0)
         * @returns a new down Vector3
         */
        Vector3.Down = function () {
            return new Vector3(0.0, -1.0, 0.0);
        };
        /**
         * Returns a new Vector3 set to (0.0, 0.0, 1.0)
         * @returns a new forward Vector3
         */
        Vector3.Forward = function () {
            return new Vector3(0.0, 0.0, 1.0);
        };
        /**
         * Returns a new Vector3 set to (0.0, 0.0, -1.0)
         * @returns a new forward Vector3
         */
        Vector3.Backward = function () {
            return new Vector3(0.0, 0.0, -1.0);
        };
        /**
         * Returns a new Vector3 set to (1.0, 0.0, 0.0)
         * @returns a new right Vector3
         */
        Vector3.Right = function () {
            return new Vector3(1.0, 0.0, 0.0);
        };
        /**
         * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
         * @returns a new left Vector3
         */
        Vector3.Left = function () {
            return new Vector3(-1.0, 0.0, 0.0);
        };
        /**
         * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
         * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
         * @param vector defines the Vector3 to transform
         * @param transformation defines the transformation matrix
         * @returns the transformed Vector3
         */
        Vector3.TransformCoordinates = function (vector, transformation) {
            var result = Vector3.Zero();
            Vector3.TransformCoordinatesToRef(vector, transformation, result);
            return result;
        };
        /**
         * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
         * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
         * @param vector defines the Vector3 to transform
         * @param transformation defines the transformation matrix
         * @param result defines the Vector3 where to store the result
         */
        Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
            var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
            var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
            result.x = x / w;
            result.y = y / w;
            result.z = z / w;
        };
        /**
         * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
         * This method computes tranformed coordinates only, not transformed direction vectors
         * @param x define the x coordinate of the source vector
         * @param y define the y coordinate of the source vector
         * @param z define the z coordinate of the source vector
         * @param transformation defines the transformation matrix
         * @param result defines the Vector3 where to store the result
         */
        Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
            var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
            var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
            var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
            var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
            result.x = rx / rw;
            result.y = ry / rw;
            result.z = rz / rw;
        };
        /**
         * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
         * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
         * @param vector defines the Vector3 to transform
         * @param transformation defines the transformation matrix
         * @returns the new Vector3
         */
        Vector3.TransformNormal = function (vector, transformation) {
            var result = Vector3.Zero();
            Vector3.TransformNormalToRef(vector, transformation, result);
            return result;
        };
        /**
         * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
         * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
         * @param vector defines the Vector3 to transform
         * @param transformation defines the transformation matrix
         * @param result defines the Vector3 where to store the result
         */
        Vector3.TransformNormalToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
            var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
            result.x = x;
            result.y = y;
            result.z = z;
        };
        /**
         * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
         * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
         * @param x define the x coordinate of the source vector
         * @param y define the y coordinate of the source vector
         * @param z define the z coordinate of the source vector
         * @param transformation defines the transformation matrix
         * @param result defines the Vector3 where to store the result
         */
        Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
            result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
            result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
            result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
        };
        /**
         * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
         * @param value1 defines the first control point
         * @param value2 defines the second control point
         * @param value3 defines the third control point
         * @param value4 defines the fourth control point
         * @param amount defines the amount on the spline to use
         * @returns the new Vector3
         */
        Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
                (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
                ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
            var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
                (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
                ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
            var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
                (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
                ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
            return new Vector3(x, y, z);
        };
        /**
         * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
         * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
         * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
         * @param value defines the current value
         * @param min defines the lower range value
         * @param max defines the upper range value
         * @returns the new Vector3
         */
        Vector3.Clamp = function (value, min, max) {
            var x = value.x;
            x = (x > max.x) ? max.x : x;
            x = (x < min.x) ? min.x : x;
            var y = value.y;
            y = (y > max.y) ? max.y : y;
            y = (y < min.y) ? min.y : y;
            var z = value.z;
            z = (z > max.z) ? max.z : z;
            z = (z < min.z) ? min.z : z;
            return new Vector3(x, y, z);
        };
        /**
         * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
         * @param value1 defines the first control point
         * @param tangent1 defines the first tangent vector
         * @param value2 defines the second control point
         * @param tangent2 defines the second tangent vector
         * @param amount defines the amount on the interpolation spline (between 0 and 1)
         * @returns the new Vector3
         */
        Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
            var part2 = (-2.0 * cubed) + (3.0 * squared);
            var part3 = (cubed - (2.0 * squared)) + amount;
            var part4 = cubed - squared;
            var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
            var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
            var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
            return new Vector3(x, y, z);
        };
        /**
         * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
         * @param start defines the start value
         * @param end defines the end value
         * @param amount max defines amount between both (between 0 and 1)
         * @returns the new Vector3
         */
        Vector3.Lerp = function (start, end, amount) {
            var result = new Vector3(0, 0, 0);
            Vector3.LerpToRef(start, end, amount, result);
            return result;
        };
        /**
         * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
         * @param start defines the start value
         * @param end defines the end value
         * @param amount max defines amount between both (between 0 and 1)
         * @param result defines the Vector3 where to store the result
         */
        Vector3.LerpToRef = function (start, end, amount, result) {
            result.x = start.x + ((end.x - start.x) * amount);
            result.y = start.y + ((end.y - start.y) * amount);
            result.z = start.z + ((end.z - start.z) * amount);
        };
        /**
         * Returns the dot product (float) between the vectors "left" and "right"
         * @param left defines the left operand
         * @param right defines the right operand
         * @returns the dot product
         */
        Vector3.Dot = function (left, right) {
            return (left.x * right.x + left.y * right.y + left.z * right.z);
        };
        /**
         * Returns a new Vector3 as the cross product of the vectors "left" and "right"
         * The cross product is then orthogonal to both "left" and "right"
         * @param left defines the left operand
         * @param right defines the right operand
         * @returns the cross product
         */
        Vector3.Cross = function (left, right) {
            var result = Vector3.Zero();
            Vector3.CrossToRef(left, right, result);
            return result;
        };
        /**
         * Sets the given vector "result" with the cross product of "left" and "right"
         * The cross product is then orthogonal to both "left" and "right"
         * @param left defines the left operand
         * @param right defines the right operand
         * @param result defines the Vector3 where to store the result
         */
        Vector3.CrossToRef = function (left, right, result) {
            MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
            MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
            MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
            result.copyFrom(MathTmp.Vector3[0]);
        };
        /**
         * Returns a new Vector3 as the normalization of the given vector
         * @param vector defines the Vector3 to normalize
         * @returns the new Vector3
         */
        Vector3.Normalize = function (vector) {
            var result = Vector3.Zero();
            Vector3.NormalizeToRef(vector, result);
            return result;
        };
        /**
         * Sets the given vector "result" with the normalization of the given first vector
         * @param vector defines the Vector3 to normalize
         * @param result defines the Vector3 where to store the result
         */
        Vector3.NormalizeToRef = function (vector, result) {
            result.copyFrom(vector);
            result.normalize();
        };
        /**
         * Project a Vector3 onto screen space
         * @param vector defines the Vector3 to project
         * @param world defines the world matrix to use
         * @param transform defines the transform (view x projection) matrix to use
         * @param viewport defines the screen viewport to use
         * @returns the new Vector3
         */
        Vector3.Project = function (vector, world, transform, viewport) {
            var cw = viewport.width;
            var ch = viewport.height;
            var cx = viewport.x;
            var cy = viewport.y;
            var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
            Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
            var matrix = MathTmp.Matrix[0];
            world.multiplyToRef(transform, matrix);
            matrix.multiplyToRef(viewportMatrix, matrix);
            return Vector3.TransformCoordinates(vector, matrix);
        };
        /**
         * Unproject from screen space to object space
         * @param source defines the screen space Vector3 to use
         * @param viewportWidth defines the current width of the viewport
         * @param viewportHeight defines the current height of the viewport
         * @param world defines the world matrix to use (can be set to Identity to go to world space)
         * @param transform defines the transform (view x projection) matrix to use
         * @returns the new Vector3
         */
        Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
            var matrix = MathTmp.Matrix[0];
            world.multiplyToRef(transform, matrix);
            matrix.invert();
            source.x = source.x / viewportWidth * 2 - 1;
            source.y = -(source.y / viewportHeight * 2 - 1);
            var vector = Vector3.TransformCoordinates(source, matrix);
            var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
            if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
                vector = vector.scale(1.0 / num);
            }
            return vector;
        };
        /**
         * Unproject from screen space to object space
         * @param source defines the screen space Vector3 to use
         * @param viewportWidth defines the current width of the viewport
         * @param viewportHeight defines the current height of the viewport
         * @param world defines the world matrix to use (can be set to Identity to go to world space)
         * @param view defines the view matrix to use
         * @param projection defines the projection matrix to use
         * @returns the new Vector3
         */
        Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
            var result = Vector3.Zero();
            Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
            return result;
        };
        /**
         * Unproject from screen space to object space
         * @param source defines the screen space Vector3 to use
         * @param viewportWidth defines the current width of the viewport
         * @param viewportHeight defines the current height of the viewport
         * @param world defines the world matrix to use (can be set to Identity to go to world space)
         * @param view defines the view matrix to use
         * @param projection defines the projection matrix to use
         * @param result defines the Vector3 where to store the result
         */
        Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
            Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
        };
        /**
         * Unproject from screen space to object space
         * @param sourceX defines the screen space x coordinate to use
         * @param sourceY defines the screen space y coordinate to use
         * @param sourceZ defines the screen space z coordinate to use
         * @param viewportWidth defines the current width of the viewport
         * @param viewportHeight defines the current height of the viewport
         * @param world defines the world matrix to use (can be set to Identity to go to world space)
         * @param view defines the view matrix to use
         * @param projection defines the projection matrix to use
         * @param result defines the Vector3 where to store the result
         */
        Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
            var matrix = MathTmp.Matrix[0];
            world.multiplyToRef(view, matrix);
            matrix.multiplyToRef(projection, matrix);
            matrix.invert();
            var screenSource = MathTmp.Vector3[0];
            screenSource.x = sourceX / viewportWidth * 2 - 1;
            screenSource.y = -(sourceY / viewportHeight * 2 - 1);
            screenSource.z = 2 * sourceZ - 1.0;
            Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
            var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
            if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
                result.scaleInPlace(1.0 / num);
            }
        };
        /**
         * Gets the minimal coordinate values between two Vector3
         * @param left defines the first operand
         * @param right defines the second operand
         * @returns the new Vector3
         */
        Vector3.Minimize = function (left, right) {
            var min = left.clone();
            min.minimizeInPlace(right);
            return min;
        };
        /**
         * Gets the maximal coordinate values between two Vector3
         * @param left defines the first operand
         * @param right defines the second operand
         * @returns the new Vector3
         */
        Vector3.Maximize = function (left, right) {
            var max = left.clone();
            max.maximizeInPlace(right);
            return max;
        };
        /**
         * Returns the distance between the vectors "value1" and "value2"
         * @param value1 defines the first operand
         * @param value2 defines the second operand
         * @returns the distance
         */
        Vector3.Distance = function (value1, value2) {
            return Math.sqrt(Vector3.DistanceSquared(value1, value2));
        };
        /**
         * Returns the squared distance between the vectors "value1" and "value2"
         * @param value1 defines the first operand
         * @param value2 defines the second operand
         * @returns the squared distance
         */
        Vector3.DistanceSquared = function (value1, value2) {
            var x = value1.x - value2.x;
            var y = value1.y - value2.y;
            var z = value1.z - value2.z;
            return (x * x) + (y * y) + (z * z);
        };
        /**
         * Returns a new Vector3 located at the center between "value1" and "value2"
         * @param value1 defines the first operand
         * @param value2 defines the second operand
         * @returns the new Vector3
         */
        Vector3.Center = function (value1, value2) {
            var center = value1.add(value2);
            center.scaleInPlace(0.5);
            return center;
        };
        /**
         * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
         * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
         * to something in order to rotate it from its local system to the given target system
         * Note: axis1, axis2 and axis3 are normalized during this operation
         * @param axis1 defines the first axis
         * @param axis2 defines the second axis
         * @param axis3 defines the third axis
         * @returns a new Vector3
         */
        Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
            var rotation = Vector3.Zero();
            Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
            return rotation;
        };
        /**
         * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
         * @param axis1 defines the first axis
         * @param axis2 defines the second axis
         * @param axis3 defines the third axis
         * @param ref defines the Vector3 where to store the result
         */
        Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
            var quat = MathTmp.Quaternion[0];
            Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
            quat.toEulerAnglesToRef(ref);
        };
        return Vector3;
    }());
    BABYLON.Vector3 = Vector3;
    /**
     * Vector4 class created for EulerAngle class conversion to Quaternion
     */
    var Vector4 = /** @class */ (function () {
        /**
         * Creates a Vector4 object from the given floats.
         * @param x x value of the vector
         * @param y y value of the vector
         * @param z z value of the vector
         * @param w w value of the vector
         */
        function Vector4(
        /** x value of the vector */
        x, 
        /** y value of the vector */
        y, 
        /** z value of the vector */
        z, 
        /** w value of the vector */
        w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
        }
        /**
         * Returns the string with the Vector4 coordinates.
         * @returns a string containing all the vector values
         */
        Vector4.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
        };
        /**
         * Returns the string "Vector4".
         * @returns "Vector4"
         */
        Vector4.prototype.getClassName = function () {
            return "Vector4";
        };
        /**
         * Returns the Vector4 hash code.
         * @returns a unique hash code
         */
        Vector4.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            hash = (hash * 397) ^ (this.z || 0);
            hash = (hash * 397) ^ (this.w || 0);
            return hash;
        };
        // Operators
        /**
         * Returns a new array populated with 4 elements : the Vector4 coordinates.
         * @returns the resulting array
         */
        Vector4.prototype.asArray = function () {
            var result = new Array();
            this.toArray(result, 0);
            return result;
        };
        /**
         * Populates the given array from the given index with the Vector4 coordinates.
         * @param array array to populate
         * @param index index of the array to start at (default: 0)
         * @returns the Vector4.
         */
        Vector4.prototype.toArray = function (array, index) {
            if (index === undefined) {
                index = 0;
            }
            array[index] = this.x;
            array[index + 1] = this.y;
            array[index + 2] = this.z;
            array[index + 3] = this.w;
            return this;
        };
        /**
         * Adds the given vector to the current Vector4.
         * @param otherVector the vector to add
         * @returns the updated Vector4.
         */
        Vector4.prototype.addInPlace = function (otherVector) {
            this.x += otherVector.x;
            this.y += otherVector.y;
            this.z += otherVector.z;
            this.w += otherVector.w;
            return this;
        };
        /**
         * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
         * @param otherVector the vector to add
         * @returns the resulting vector
         */
        Vector4.prototype.add = function (otherVector) {
            return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
        };
        /**
         * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
         * @param otherVector the vector to add
         * @param result the vector to store the result
         * @returns the current Vector4.
         */
        Vector4.prototype.addToRef = function (otherVector, result) {
            result.x = this.x + otherVector.x;
            result.y = this.y + otherVector.y;
            result.z = this.z + otherVector.z;
            result.w = this.w + otherVector.w;
            return this;
        };
        /**
         * Subtract in place the given vector from the current Vector4.
         * @param otherVector the vector to subtract
         * @returns the updated Vector4.
         */
        Vector4.prototype.subtractInPlace = function (otherVector) {
            this.x -= otherVector.x;
            this.y -= otherVector.y;
            this.z -= otherVector.z;
            this.w -= otherVector.w;
            return this;
        };
        /**
         * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
         * @param otherVector the vector to add
         * @returns the new vector with the result
         */
        Vector4.prototype.subtract = function (otherVector) {
            return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
        };
        /**
         * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
         * @param otherVector the vector to subtract
         * @param result the vector to store the result
         * @returns the current Vector4.
         */
        Vector4.prototype.subtractToRef = function (otherVector, result) {
            result.x = this.x - otherVector.x;
            result.y = this.y - otherVector.y;
            result.z = this.z - otherVector.z;
            result.w = this.w - otherVector.w;
            return this;
        };
        /**
         * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
         */
        /**
         * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
         * @param x value to subtract
         * @param y value to subtract
         * @param z value to subtract
         * @param w value to subtract
         * @returns new vector containing the result
         */
        Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
            return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
        };
        /**
         * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
         * @param x value to subtract
         * @param y value to subtract
         * @param z value to subtract
         * @param w value to subtract
         * @param result the vector to store the result in
         * @returns the current Vector4.
         */
        Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
            result.x = this.x - x;
            result.y = this.y - y;
            result.z = this.z - z;
            result.w = this.w - w;
            return this;
        };
        /**
         * Returns a new Vector4 set with the current Vector4 negated coordinates.
         * @returns a new vector with the negated values
         */
        Vector4.prototype.negate = function () {
            return new Vector4(-this.x, -this.y, -this.z, -this.w);
        };
        /**
         * Multiplies the current Vector4 coordinates by scale (float).
         * @param scale the number to scale with
         * @returns the updated Vector4.
         */
        Vector4.prototype.scaleInPlace = function (scale) {
            this.x *= scale;
            this.y *= scale;
            this.z *= scale;
            this.w *= scale;
            return this;
        };
        /**
         * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
         * @param scale the number to scale with
         * @returns a new vector with the result
         */
        Vector4.prototype.scale = function (scale) {
            return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
        };
        /**
         * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
         * @param scale the number to scale with
         * @param result a vector to store the result in
         * @returns the current Vector4.
         */
        Vector4.prototype.scaleToRef = function (scale, result) {
            result.x = this.x * scale;
            result.y = this.y * scale;
            result.z = this.z * scale;
            result.w = this.w * scale;
            return this;
        };
        /**
         * Scale the current Vector4 values by a factor and add the result to a given Vector4
         * @param scale defines the scale factor
         * @param result defines the Vector4 object where to store the result
         * @returns the unmodified current Vector4
         */
        Vector4.prototype.scaleAndAddToRef = function (scale, result) {
            result.x += this.x * scale;
            result.y += this.y * scale;
            result.z += this.z * scale;
            result.w += this.w * scale;
            return this;
        };
        /**
         * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
         * @param otherVector the vector to compare against
         * @returns true if they are equal
         */
        Vector4.prototype.equals = function (otherVector) {
            return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
        };
        /**
         * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
         * @param otherVector vector to compare against
         * @param epsilon (Default: very small number)
         * @returns true if they are equal
         */
        Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
            if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
            return otherVector
                && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
                && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
                && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
                && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
        };
        /**
         * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
         * @param x x value to compare against
         * @param y y value to compare against
         * @param z z value to compare against
         * @param w w value to compare against
         * @returns true if equal
         */
        Vector4.prototype.equalsToFloats = function (x, y, z, w) {
            return this.x === x && this.y === y && this.z === z && this.w === w;
        };
        /**
         * Multiplies in place the current Vector4 by the given one.
         * @param otherVector vector to multiple with
         * @returns the updated Vector4.
         */
        Vector4.prototype.multiplyInPlace = function (otherVector) {
            this.x *= otherVector.x;
            this.y *= otherVector.y;
            this.z *= otherVector.z;
            this.w *= otherVector.w;
            return this;
        };
        /**
         * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
         * @param otherVector vector to multiple with
         * @returns resulting new vector
         */
        Vector4.prototype.multiply = function (otherVector) {
            return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
        };
        /**
         * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
         * @param otherVector vector to multiple with
         * @param result vector to store the result
         * @returns the current Vector4.
         */
        Vector4.prototype.multiplyToRef = function (otherVector, result) {
            result.x = this.x * otherVector.x;
            result.y = this.y * otherVector.y;
            result.z = this.z * otherVector.z;
            result.w = this.w * otherVector.w;
            return this;
        };
        /**
         * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
         * @param x x value multiply with
         * @param y y value multiply with
         * @param z z value multiply with
         * @param w w value multiply with
         * @returns resulting new vector
         */
        Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
            return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
        };
        /**
         * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
         * @param otherVector vector to devide with
         * @returns resulting new vector
         */
        Vector4.prototype.divide = function (otherVector) {
            return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
        };
        /**
         * Updates the given vector "result" with the division result of the current Vector4 by the given one.
         * @param otherVector vector to devide with
         * @param result vector to store the result
         * @returns the current Vector4.
         */
        Vector4.prototype.divideToRef = function (otherVector, result) {
            result.x = this.x / otherVector.x;
            result.y = this.y / otherVector.y;
            result.z = this.z / otherVector.z;
            result.w = this.w / otherVector.w;
            return this;
        };
        /**
         * Divides the current Vector3 coordinates by the given ones.
         * @param otherVector vector to devide with
         * @returns the updated Vector3.
         */
        Vector4.prototype.divideInPlace = function (otherVector) {
            return this.divideToRef(otherVector, this);
        };
        /**
         * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
         * @param other defines the second operand
         * @returns the current updated Vector4
         */
        Vector4.prototype.minimizeInPlace = function (other) {
            if (other.x < this.x) {
                this.x = other.x;
            }
            if (other.y < this.y) {
                this.y = other.y;
            }
            if (other.z < this.z) {
                this.z = other.z;
            }
            if (other.w < this.w) {
                this.w = other.w;
            }
            return this;
        };
        /**
         * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
         * @param other defines the second operand
         * @returns the current updated Vector4
         */
        Vector4.prototype.maximizeInPlace = function (other) {
            if (other.x > this.x) {
                this.x = other.x;
            }
            if (other.y > this.y) {
                this.y = other.y;
            }
            if (other.z > this.z) {
                this.z = other.z;
            }
            if (other.w > this.w) {
                this.w = other.w;
            }
            return this;
        };
        /**
         * Gets a new Vector4 from current Vector4 floored values
         * @returns a new Vector4
         */
        Vector4.prototype.floor = function () {
            return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
        };
        /**
         * Gets a new Vector4 from current Vector3 floored values
         * @returns a new Vector4
         */
        Vector4.prototype.fract = function () {
            return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
        };
        // Properties
        /**
         * Returns the Vector4 length (float).
         * @returns the length
         */
        Vector4.prototype.length = function () {
            return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
        };
        /**
         * Returns the Vector4 squared length (float).
         * @returns the length squared
         */
        Vector4.prototype.lengthSquared = function () {
            return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
        };
        // Methods
        /**
         * Normalizes in place the Vector4.
         * @returns the updated Vector4.
         */
        Vector4.prototype.normalize = function () {
            var len = this.length();
            if (len === 0) {
                return this;
            }
            var num = 1.0 / len;
            this.x *= num;
            this.y *= num;
            this.z *= num;
            this.w *= num;
            return this;
        };
        /**
         * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
         * @returns this converted to a new vector3
         */
        Vector4.prototype.toVector3 = function () {
            return new Vector3(this.x, this.y, this.z);
        };
        /**
         * Returns a new Vector4 copied from the current one.
         * @returns the new cloned vector
         */
        Vector4.prototype.clone = function () {
            return new Vector4(this.x, this.y, this.z, this.w);
        };
        /**
         * Updates the current Vector4 with the given one coordinates.
         * @param source the source vector to copy from
         * @returns the updated Vector4.
         */
        Vector4.prototype.copyFrom = function (source) {
            this.x = source.x;
            this.y = source.y;
            this.z = source.z;
            this.w = source.w;
            return this;
        };
        /**
         * Updates the current Vector4 coordinates with the given floats.
         * @param x float to copy from
         * @param y float to copy from
         * @param z float to copy from
         * @param w float to copy from
         * @returns the updated Vector4.
         */
        Vector4.prototype.copyFromFloats = function (x, y, z, w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
            return this;
        };
        /**
         * Updates the current Vector4 coordinates with the given floats.
         * @param x float to set from
         * @param y float to set from
         * @param z float to set from
         * @param w float to set from
         * @returns the updated Vector4.
         */
        Vector4.prototype.set = function (x, y, z, w) {
            return this.copyFromFloats(x, y, z, w);
        };
        // Statics
        /**
         * Returns a new Vector4 set from the starting index of the given array.
         * @param array the array to pull values from
         * @param offset the offset into the array to start at
         * @returns the new vector
         */
        Vector4.FromArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
        };
        /**
         * Updates the given vector "result" from the starting index of the given array.
         * @param array the array to pull values from
         * @param offset the offset into the array to start at
         * @param result the vector to store the result in
         */
        Vector4.FromArrayToRef = function (array, offset, result) {
            result.x = array[offset];
            result.y = array[offset + 1];
            result.z = array[offset + 2];
            result.w = array[offset + 3];
        };
        /**
         * Updates the given vector "result" from the starting index of the given Float32Array.
         * @param array the array to pull values from
         * @param offset the offset into the array to start at
         * @param result the vector to store the result in
         */
        Vector4.FromFloatArrayToRef = function (array, offset, result) {
            Vector4.FromArrayToRef(array, offset, result);
        };
        /**
         * Updates the given vector "result" coordinates from the given floats.
         * @param x float to set from
         * @param y float to set from
         * @param z float to set from
         * @param w float to set from
         * @param result the vector to the floats in
         */
        Vector4.FromFloatsToRef = function (x, y, z, w, result) {
            result.x = x;
            result.y = y;
            result.z = z;
            result.w = w;
        };
        /**
         * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
         * @returns the new vector
         */
        Vector4.Zero = function () {
            return new Vector4(0.0, 0.0, 0.0, 0.0);
        };
        /**
         * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
         * @returns the new vector
         */
        Vector4.One = function () {
            return new Vector4(1.0, 1.0, 1.0, 1.0);
        };
        /**
         * Returns a new normalized Vector4 from the given one.
         * @param vector the vector to normalize
         * @returns the vector
         */
        Vector4.Normalize = function (vector) {
            var result = Vector4.Zero();
            Vector4.NormalizeToRef(vector, result);
            return result;
        };
        /**
         * Updates the given vector "result" from the normalization of the given one.
         * @param vector the vector to normalize
         * @param result the vector to store the result in
         */
        Vector4.NormalizeToRef = function (vector, result) {
            result.copyFrom(vector);
            result.normalize();
        };
        /**
         * Returns a vector with the minimum values from the left and right vectors
         * @param left left vector to minimize
         * @param right right vector to minimize
         * @returns a new vector with the minimum of the left and right vector values
         */
        Vector4.Minimize = function (left, right) {
            var min = left.clone();
            min.minimizeInPlace(right);
            return min;
        };
        /**
         * Returns a vector with the maximum values from the left and right vectors
         * @param left left vector to maximize
         * @param right right vector to maximize
         * @returns a new vector with the maximum of the left and right vector values
         */
        Vector4.Maximize = function (left, right) {
            var max = left.clone();
            max.maximizeInPlace(right);
            return max;
        };
        /**
         * Returns the distance (float) between the vectors "value1" and "value2".
         * @param value1 value to calulate the distance between
         * @param value2 value to calulate the distance between
         * @return the distance between the two vectors
         */
        Vector4.Distance = function (value1, value2) {
            return Math.sqrt(Vector4.DistanceSquared(value1, value2));
        };
        /**
         * Returns the squared distance (float) between the vectors "value1" and "value2".
         * @param value1 value to calulate the distance between
         * @param value2 value to calulate the distance between
         * @return the distance between the two vectors squared
         */
        Vector4.DistanceSquared = function (value1, value2) {
            var x = value1.x - value2.x;
            var y = value1.y - value2.y;
            var z = value1.z - value2.z;
            var w = value1.w - value2.w;
            return (x * x) + (y * y) + (z * z) + (w * w);
        };
        /**
         * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
         * @param value1 value to calulate the center between
         * @param value2 value to calulate the center between
         * @return the center between the two vectors
         */
        Vector4.Center = function (value1, value2) {
            var center = value1.add(value2);
            center.scaleInPlace(0.5);
            return center;
        };
        /**
         * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
         * This methods computes transformed normalized direction vectors only.
         * @param vector the vector to transform
         * @param transformation the transformation matrix to apply
         * @returns the new vector
         */
        Vector4.TransformNormal = function (vector, transformation) {
            var result = Vector4.Zero();
            Vector4.TransformNormalToRef(vector, transformation, result);
            return result;
        };
        /**
         * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
         * This methods computes transformed normalized direction vectors only.
         * @param vector the vector to transform
         * @param transformation the transformation matrix to apply
         * @param result the vector to store the result in
         */
        Vector4.TransformNormalToRef = function (vector, transformation, result) {
            var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
            var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
            var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
            result.x = x;
            result.y = y;
            result.z = z;
            result.w = vector.w;
        };
        /**
         * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
         * This methods computes transformed normalized direction vectors only.
         * @param x value to transform
         * @param y value to transform
         * @param z value to transform
         * @param w value to transform
         * @param transformation the transformation matrix to apply
         * @param result the vector to store the results in
         */
        Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
            result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
            result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
            result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
            result.w = w;
        };
        return Vector4;
    }());
    BABYLON.Vector4 = Vector4;
    /**
     * Size containing widht and height
     */
    var Size = /** @class */ (function () {
        /**
         * Creates a Size object from the given width and height (floats).
         * @param width width of the new size
         * @param height height of the new size
         */
        function Size(width, height) {
            this.width = width;
            this.height = height;
        }
        /**
         * Returns a string with the Size width and height
         * @returns a string with the Size width and height
         */
        Size.prototype.toString = function () {
            return "{W: " + this.width + ", H: " + this.height + "}";
        };
        /**
         * "Size"
         * @returns the string "Size"
         */
        Size.prototype.getClassName = function () {
            return "Size";
        };
        /**
         * Returns the Size hash code.
         * @returns a hash code for a unique width and height
         */
        Size.prototype.getHashCode = function () {
            var hash = this.width || 0;
            hash = (hash * 397) ^ (this.height || 0);
            return hash;
        };
        /**
         * Updates the current size from the given one.
         * @param src the given size
         */
        Size.prototype.copyFrom = function (src) {
            this.width = src.width;
            this.height = src.height;
        };
        /**
         * Updates in place the current Size from the given floats.
         * @param width width of the new size
         * @param height height of the new size
         * @returns the updated Size.
         */
        Size.prototype.copyFromFloats = function (width, height) {
            this.width = width;
            this.height = height;
            return this;
        };
        /**
         * Updates in place the current Size from the given floats.
         * @param width width to set
         * @param height height to set
         * @returns the updated Size.
         */
        Size.prototype.set = function (width, height) {
            return this.copyFromFloats(width, height);
        };
        /**
         * Multiplies the width and height by numbers
         * @param w factor to multiple the width by
         * @param h factor to multiple the height by
         * @returns a new Size set with the multiplication result of the current Size and the given floats.
         */
        Size.prototype.multiplyByFloats = function (w, h) {
            return new Size(this.width * w, this.height * h);
        };
        /**
         * Clones the size
         * @returns a new Size copied from the given one.
         */
        Size.prototype.clone = function () {
            return new Size(this.width, this.height);
        };
        /**
         * True if the current Size and the given one width and height are strictly equal.
         * @param other the other size to compare against
         * @returns True if the current Size and the given one width and height are strictly equal.
         */
        Size.prototype.equals = function (other) {
            if (!other) {
                return false;
            }
            return (this.width === other.width) && (this.height === other.height);
        };
        Object.defineProperty(Size.prototype, "surface", {
            /**
             * The surface of the Size : width * height (float).
             */
            get: function () {
                return this.width * this.height;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Create a new size of zero
         * @returns a new Size set to (0.0, 0.0)
         */
        Size.Zero = function () {
            return new Size(0.0, 0.0);
        };
        /**
         * Sums the width and height of two sizes
         * @param otherSize size to add to this size
         * @returns a new Size set as the addition result of the current Size and the given one.
         */
        Size.prototype.add = function (otherSize) {
            var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
            return r;
        };
        /**
         * Subtracts the width and height of two
         * @param otherSize size to subtract to this size
         * @returns a new Size set as the subtraction result of  the given one from the current Size.
         */
        Size.prototype.subtract = function (otherSize) {
            var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
            return r;
        };
        /**
         * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
         * @param start starting size to lerp between
         * @param end end size to lerp between
         * @param amount amount to lerp between the start and end values
         * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
         */
        Size.Lerp = function (start, end, amount) {
            var w = start.width + ((end.width - start.width) * amount);
            var h = start.height + ((end.height - start.height) * amount);
            return new Size(w, h);
        };
        return Size;
    }());
    BABYLON.Size = Size;
    /**
     * Class used to store quaternion data
     * @see https://en.wikipedia.org/wiki/Quaternion
     * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
     */
    var Quaternion = /** @class */ (function () {
        /**
         * Creates a new Quaternion from the given floats
         * @param x defines the first component (0 by default)
         * @param y defines the second component (0 by default)
         * @param z defines the third component (0 by default)
         * @param w defines the fourth component (1.0 by default)
         */
        function Quaternion(
        /** defines the first component (0 by default) */
        x, 
        /** defines the second component (0 by default) */
        y, 
        /** defines the third component (0 by default) */
        z, 
        /** defines the fourth component (1.0 by default) */
        w) {
            if (x === void 0) { x = 0.0; }
            if (y === void 0) { y = 0.0; }
            if (z === void 0) { z = 0.0; }
            if (w === void 0) { w = 1.0; }
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
        }
        /**
         * Gets a string representation for the current quaternion
         * @returns a string with the Quaternion coordinates
         */
        Quaternion.prototype.toString = function () {
            return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
        };
        /**
         * Gets the class name of the quaternion
         * @returns the string "Quaternion"
         */
        Quaternion.prototype.getClassName = function () {
            return "Quaternion";
        };
        /**
         * Gets a hash code for this quaternion
         * @returns the quaternion hash code
         */
        Quaternion.prototype.getHashCode = function () {
            var hash = this.x || 0;
            hash = (hash * 397) ^ (this.y || 0);
            hash = (hash * 397) ^ (this.z || 0);
            hash = (hash * 397) ^ (this.w || 0);
            return hash;
        };
        /**
         * Copy the quaternion to an array
         * @returns a new array populated with 4 elements from the quaternion coordinates
         */
        Quaternion.prototype.asArray = function () {
            return [this.x, this.y, this.z, this.w];
        };
        /**
         * Check if two quaternions are equals
         * @param otherQuaternion defines the second operand
         * @return true if the current quaternion and the given one coordinates are strictly equals
         */
        Quaternion.prototype.equals = function (otherQuaternion) {
            return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
        };
        /**
         * Clone the current quaternion
         * @returns a new quaternion copied from the current one
         */
        Quaternion.prototype.clone = function () {
            return new Quaternion(this.x, this.y, this.z, this.w);
        };
        /**
         * Copy a quaternion to the current one
         * @param other defines the other quaternion
         * @returns the updated current quaternion
         */
        Quaternion.prototype.copyFrom = function (other) {
            this.x = other.x;
            this.y = other.y;
            this.z = other.z;
            this.w = other.w;
            return this;
        };
        /**
         * Updates the current quaternion with the given float coordinates
         * @param x defines the x coordinate
         * @param y defines the y coordinate
         * @param z defines the z coordinate
         * @param w defines the w coordinate
         * @returns the updated current quaternion
         */
        Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
            this.x = x;
            this.y = y;
            this.z = z;
            this.w = w;
            return this;
        };
        /**
         * Updates the current quaternion from the given float coordinates
         * @param x defines the x coordinate
         * @param y defines the y coordinate
         * @param z defines the z coordinate
         * @param w defines the w coordinate
         * @returns the updated current quaternion
         */
        Quaternion.prototype.set = function (x, y, z, w) {
            return this.copyFromFloats(x, y, z, w);
        };
        /**
         * Adds two quaternions
         * @param other defines the second operand
         * @returns a new quaternion as the addition result of the given one and the current quaternion
         */
        Quaternion.prototype.add = function (other) {
            return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
        };
        /**
         * Add a quaternion to the current one
         * @param other defines the quaternion to add
         * @returns the current quaternion
         */
        Quaternion.prototype.addInPlace = function (other) {
            this.x += other.x;
            this.y += other.y;
            this.z += other.z;
            this.w += other.w;
            return this;
        };
        /**
         * Subtract two quaternions
         * @param other defines the second operand
         * @returns a new quaternion as the subtraction result of the given one from the current one
         */
        Quaternion.prototype.subtract = function (other) {
            return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
        };
        /**
         * Multiplies the current quaternion by a scale factor
         * @param value defines the scale factor
         * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
         */
        Quaternion.prototype.scale = function (value) {
            return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
        };
        /**
         * Scale the current quaternion values by a factor and stores the result to a given quaternion
         * @param scale defines the scale factor
         * @param result defines the Quaternion object where to store the result
         * @returns the unmodified current quaternion
         */
        Quaternion.prototype.scaleToRef = function (scale, result) {
            result.x = this.x * scale;
            result.y = this.y * scale;
            result.z = this.z * scale;
            result.w = this.w * scale;
            return this;
        };
        /**
         * Multiplies in place the current quaternion by a scale factor
         * @param value defines the scale factor
         * @returns the current modified quaternion
         */
        Quaternion.prototype.scaleInPlace = function (value) {
            this.x *= value;
            this.y *= value;
            this.z *= value;
            this.w *= value;
            return this;
        };
        /**
         * Scale the current quaternion values by a factor and add the result to a given quaternion
         * @param scale defines the scale factor
         * @param result defines the Quaternion object where to store the result
         * @returns the unmodified current quaternion
         */
        Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
            result.x += this.x * scale;
            result.y += this.y * scale;
            result.z += this.z * scale;
            result.w += this.w * scale;
            return this;
        };
        /**
         * Multiplies two quaternions
         * @param q1 defines the second operand
         * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
         */
        Quaternion.prototype.multiply = function (q1) {
            var result = new Quaternion(0, 0, 0, 1.0);
            this.multiplyToRef(q1, result);
            return result;
        };
        /**
         * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
         * @param q1 defines the second operand
         * @param result defines the target quaternion
         * @returns the current quaternion
         */
        Quaternion.prototype.multiplyToRef = function (q1, result) {
            var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
            var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
            var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
            var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
            result.copyFromFloats(x, y, z, w);
            return this;
        };
        /**
         * Updates the current quaternion with the multiplication of itself with the given one "q1"
         * @param q1 defines the second operand
         * @returns the currentupdated quaternion
         */
        Quaternion.prototype.multiplyInPlace = function (q1) {
            this.multiplyToRef(q1, this);
            return this;
        };
        /**
         * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
         * @param ref defines the target quaternion
         * @returns the current quaternion
         */
        Quaternion.prototype.conjugateToRef = function (ref) {
            ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
            return this;
        };
        /**
         * Conjugates in place (1-q) the current quaternion
         * @returns the current updated quaternion
         */
        Quaternion.prototype.conjugateInPlace = function () {
            this.x *= -1;
            this.y *= -1;
            this.z *= -1;
            return this;
        };
        /**
         * Conjugates in place (1-q) the current quaternion
         * @returns a new quaternion
         */
        Quaternion.prototype.conjugate = function () {
            var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
            return result;
        };
        /**
         * Gets length of current quaternion
         * @returns the quaternion length (float)
         */
        Quaternion.prototype.length = function () {
            return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
        };
        /**
         * Normalize in place the current quaternion
         * @returns the current updated quaternion
         */
        Quaternion.prototype.normalize = function () {
            var length = 1.0 / this.length();
            this.x *= length;
            this.y *= length;
            this.z *= length;
            this.w *= length;
            return this;
        };
        /**
         * Returns a new Vector3 set with the Euler angles translated from the current quaternion
         * @param order is a reserved parameter and is ignore for now
         * @returns a new Vector3 containing the Euler angles
         */
        Quaternion.prototype.toEulerAngles = function (order) {
            if (order === void 0) { order = "YZX"; }
            var result = Vector3.Zero();
            this.toEulerAnglesToRef(result, order);
            return result;
        };
        /**
         * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
         * @param result defines the vector which will be filled with the Euler angles
         * @param order is a reserved parameter and is ignore for now
         * @returns the current unchanged quaternion
         */
        Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
            if (order === void 0) { order = "YZX"; }
            var qz = this.z;
            var qx = this.x;
            var qy = this.y;
            var qw = this.w;
            var sqw = qw * qw;
            var sqz = qz * qz;
            var sqx = qx * qx;
            var sqy = qy * qy;
            var zAxisY = qy * qz - qx * qw;
            var limit = .4999999;
            if (zAxisY < -limit) {
                result.y = 2 * Math.atan2(qy, qw);
                result.x = Math.PI / 2;
                result.z = 0;
            }
            else if (zAxisY > limit) {
                result.y = 2 * Math.atan2(qy, qw);
                result.x = -Math.PI / 2;
                result.z = 0;
            }
            else {
                result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
                result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
                result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
            }
            return this;
        };
        /**
         * Updates the given rotation matrix with the current quaternion values
         * @param result defines the target matrix
         * @returns the current unchanged quaternion
         */
        Quaternion.prototype.toRotationMatrix = function (result) {
            var xx = this.x * this.x;
            var yy = this.y * this.y;
            var zz = this.z * this.z;
            var xy = this.x * this.y;
            var zw = this.z * this.w;
            var zx = this.z * this.x;
            var yw = this.y * this.w;
            var yz = this.y * this.z;
            var xw = this.x * this.w;
            result.m[0] = 1.0 - (2.0 * (yy + zz));
            result.m[1] = 2.0 * (xy + zw);
            result.m[2] = 2.0 * (zx - yw);
            result.m[3] = 0;
            result.m[4] = 2.0 * (xy - zw);
            result.m[5] = 1.0 - (2.0 * (zz + xx));
            result.m[6] = 2.0 * (yz + xw);
            result.m[7] = 0;
            result.m[8] = 2.0 * (zx + yw);
            result.m[9] = 2.0 * (yz - xw);
            result.m[10] = 1.0 - (2.0 * (yy + xx));
            result.m[11] = 0;
            result.m[12] = 0;
            result.m[13] = 0;
            result.m[14] = 0;
            result.m[15] = 1.0;
            result._markAsUpdated();
            return this;
        };
        /**
         * Updates the current quaternion from the given rotation matrix values
         * @param matrix defines the source matrix
         * @returns the current updated quaternion
         */
        Quaternion.prototype.fromRotationMatrix = function (matrix) {
            Quaternion.FromRotationMatrixToRef(matrix, this);
            return this;
        };
        // Statics
        /**
         * Creates a new quaternion from a rotation matrix
         * @param matrix defines the source matrix
         * @returns a new quaternion created from the given rotation matrix values
         */
        Quaternion.FromRotationMatrix = function (matrix) {
            var result = new Quaternion();
            Quaternion.FromRotationMatrixToRef(matrix, result);
            return result;
        };
        /**
         * Updates the given quaternion with the given rotation matrix values
         * @param matrix defines the source matrix
         * @param result defines the target quaternion
         */
        Quaternion.FromRotationMatrixToRef = function (matrix, result) {
            var data = matrix.m;
            var m11 = data[0], m12 = data[4], m13 = data[8];
            var m21 = data[1], m22 = data[5], m23 = data[9];
            var m31 = data[2], m32 = data[6], m33 = data[10];
            var trace = m11 + m22 + m33;
            var s;
            if (trace > 0) {
                s = 0.5 / Math.sqrt(trace + 1.0);
                result.w = 0.25 / s;
                result.x = (m32 - m23) * s;
                result.y = (m13 - m31) * s;
                result.z = (m21 - m12) * s;
            }
            else if (m11 > m22 && m11 > m33) {
                s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
                result.w = (m32 - m23) / s;
                result.x = 0.25 * s;
                result.y = (m12 + m21) / s;
                result.z = (m13 + m31) / s;
            }
            else if (m22 > m33) {
                s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
                result.w = (m13 - m31) / s;
                result.x = (m12 + m21) / s;
                result.y = 0.25 * s;
                result.z = (m23 + m32) / s;
            }
            else {
                s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
                result.w = (m21 - m12) / s;
                result.x = (m13 + m31) / s;
                result.y = (m23 + m32) / s;
                result.z = 0.25 * s;
            }
        };
        /**
         * Returns the dot product (float) between the quaternions "left" and "right"
         * @param left defines the left operand
         * @param right defines the right operand
         * @returns the dot product
         */
        Quaternion.Dot = function (left, right) {
            return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
        };
        /**
         * Checks if the two quaternions are close to each other
         * @param quat0 defines the first quaternion to check
         * @param quat1 defines the second quaternion to check
         * @returns true if the two quaternions are close to each other
         */
        Quaternion.AreClose = function (quat0, quat1) {
            var dot = Quaternion.Dot(quat0, quat1);
            return dot >= 0;
        };
        /**
         * Creates an empty quaternion
         * @returns a new quaternion set to (0.0, 0.0, 0.0)
         */
        Quaternion.Zero = function () {
            return new Quaternion(0.0, 0.0, 0.0, 0.0);
        };
        /**
         * Inverse a given quaternion
         * @param q defines the source quaternion
         * @returns a new quaternion as the inverted current quaternion
         */
        Quaternion.Inverse = function (q) {
            return new Quaternion(-q.x, -q.y, -q.z, q.w);
        };
        /**
         * Creates an identity quaternion
         * @returns the identity quaternion
         */
        Quaternion.Identity = function () {
            return new Quaternion(0.0, 0.0, 0.0, 1.0);
        };
        /**
         * Gets a boolean indicating if the given quaternion is identity
         * @param quaternion defines the quaternion to check
         * @returns true if the quaternion is identity
         */
        Quaternion.IsIdentity = function (quaternion) {
            return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
        };
        /**
         * Creates a quaternion from a rotation around an axis
         * @param axis defines the axis to use
         * @param angle defines the angle to use
         * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
         */
        Quaternion.RotationAxis = function (axis, angle) {
            return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
        };
        /**
         * Creates a rotation around an axis and stores it into the given quaternion
         * @param axis defines the axis to use
         * @param angle defines the angle to use
         * @param result defines the target quaternion
         * @returns the target quaternion
         */
        Quaternion.RotationAxisToRef = function (axis, angle, result) {
            var sin = Math.sin(angle / 2);
            axis.normalize();
            result.w = Math.cos(angle / 2);
            result.x = axis.x * sin;
            result.y = axis.y * sin;
            result.z = axis.z * sin;
            return result;
        };
        /**
         * Creates a new quaternion from data stored into an array
         * @param array defines the data source
         * @param offset defines the offset in the source array where the data starts
         * @returns a new quaternion
         */
        Quaternion.FromArray = function (array, offset) {
            if (!offset) {
                offset = 0;
            }
            return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
        };
        /**
         * Creates a new quaternion from the given Euler float angles (y, x, z)
         * @param yaw defines the rotation around Y axis
         * @param pitch defines the rotation around X axis
         * @param roll defines the rotation around Z axis
         * @returns the new quaternion
         */
        Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
            var q = new Quaternion();
            Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
            return q;
        };
        /**
         * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
         * @param yaw defines the rotation around Y axis
         * @param pitch defines the rotation around X axis
         * @param roll defines the rotation around Z axis
         * @param result defines the target quaternion
         */
        Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
            // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
            var halfRoll = roll * 0.5;
            var halfPitch = pitch * 0.5;
            var halfYaw = yaw * 0.5;
            var sinRoll = Math.sin(halfRoll);
            var cosRoll = Math.cos(halfRoll);
            var sinPitch = Math.sin(halfPitch);
            var cosPitch = Math.cos(halfPitch);
            var sinYaw = Math.sin(halfYaw);
            var cosYaw = Math.cos(halfYaw);
            result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
            result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
            result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
            result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
        };
        /**
         * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
         * @param alpha defines the rotation around first axis
         * @param beta defines the rotation around second axis
         * @param gamma defines the rotation around third axis
         * @returns the new quaternion
         */
        Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
            var result = new Quaternion();
            Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
            return result;
        };
        /**
         * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
         * @param alpha defines the rotation around first axis
         * @param beta defines the rotation around second axis
         * @param gamma defines the rotation around third axis
         * @param result defines the target quaternion
         */
        Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
            // Produces a quaternion from Euler angles in the z-x-z orientation
            var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
            var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
            var halfBeta = beta * 0.5;
            result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
            result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
            result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
            result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
        };
        /**
         * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
         * @param axis1 defines the first axis
         * @param axis2 defines the second axis
         * @param axis3 defines the third axis
         * @returns the new quaternion
         */
        Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
            var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
            Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
            return quat;
        };
        /**
         * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
         * @param axis1 defines the first axis
         * @param axis2 defines the second axis
         * @param axis3 defines the third axis
         * @param ref defines the target quaternion
         */
        Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
            var rotMat = MathTmp.Matrix[0];
            Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
            Quaternion.FromRotationMatrixToRef(rotMat, ref);
        };
        /**
         * Interpolates between two quaternions
         * @param left defines first quaternion
         * @param right defines second quaternion
         * @param amount defines the gradient to use
         * @returns the new interpolated quaternion
         */
        Quaternion.Slerp = function (left, right, amount) {
            var result = Quaternion.Identity();
            Quaternion.SlerpToRef(left, right, amount, result);
            return result;
        };
        /**
         * Interpolates between two quaternions and stores it into a target quaternion
         * @param left defines first quaternion
         * @param right defines second quaternion
         * @param amount defines the gradient to use
         * @param result defines the target quaternion
         */
        Quaternion.SlerpToRef = function (left, right, amount, result) {
            var num2;
            var num3;
            var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
            var flag = false;
            if (num4 < 0) {
                flag = true;
                num4 = -num4;
            }
            if (num4 > 0.999999) {
                num3 = 1 - amount;
                num2 = flag ? -amount : amount;
            }
            else {
                var num5 = Math.acos(num4);
                var num6 = (1.0 / Math.sin(num5));
                num3 = (Math.sin((1.0 - amount) * num5)) * num6;
                num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
            }
            result.x = (num3 * left.x) + (num2 * right.x);
            result.y = (num3 * left.y) + (num2 * right.y);
            result.z = (num3 * left.z) + (num2 * right.z);
            result.w = (num3 * left.w) + (num2 * right.w);
        };
        /**
         * Interpolate between two quaternions using Hermite interpolation
         * @param value1 defines first quaternion
         * @param tangent1 defines the incoming tangent
         * @param value2 defines second quaternion
         * @param tangent2 defines the outgoing tangent
         * @param amount defines the target quaternion
         * @returns the new interpolated quaternion
         */
        Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
            var part2 = (-2.0 * cubed) + (3.0 * squared);
            var part3 = (cubed - (2.0 * squared)) + amount;
            var part4 = cubed - squared;
            var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
            var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
            var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
            var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
            return new Quaternion(x, y, z, w);
        };
        return Quaternion;
    }());
    BABYLON.Quaternion = Quaternion;
    /**
     * Class used to store matrix data (4x4)
     */
    var Matrix = /** @class */ (function () {
        /**
         * Creates an empty matrix (filled with zeros)
         */
        function Matrix() {
            this._isIdentity = false;
            this._isIdentityDirty = true;
            /**
             * Gets or sets the internal data of the matrix
             */
            this.m = new Float32Array(16);
            this._markAsUpdated();
        }
        /** @hidden */
        Matrix.prototype._markAsUpdated = function () {
            this.updateFlag = Matrix._updateFlagSeed++;
            this._isIdentityDirty = true;
        };
        // Properties
        /**
         * Check if the current matrix is indentity
         * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
         * @returns true is the matrix is the identity matrix
         */
        Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
            if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
            if (this._isIdentityDirty) {
                this._isIdentityDirty = false;
                if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
                    this._isIdentity = false;
                }
                else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
                    this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
                    this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
                    this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
                    this._isIdentity = false;
                }
                else {
                    this._isIdentity = true;
                }
                if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
                    this._isIdentity = false;
                }
            }
            return this._isIdentity;
        };
        /**
         * Gets the determinant of the matrix
         * @returns the matrix determinant
         */
        Matrix.prototype.determinant = function () {
            var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
            var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
            var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
            var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
            var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
            var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
            return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
                (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
                (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
        };
        // Methods
        /**
         * Returns the matrix as a Float32Array
         * @returns the matrix underlying array
         */
        Matrix.prototype.toArray = function () {
            return this.m;
        };
        /**
         * Returns the matrix as a Float32Array
        * @returns the matrix underlying array.
        */
        Matrix.prototype.asArray = function () {
            return this.toArray();
        };
        /**
         * Inverts the current matrix in place
         * @returns the current inverted matrix
         */
        Matrix.prototype.invert = function () {
            this.invertToRef(this);
            return this;
        };
        /**
         * Sets all the matrix elements to zero
         * @returns the current matrix
         */
        Matrix.prototype.reset = function () {
            for (var index = 0; index < 16; index++) {
                this.m[index] = 0.0;
            }
            this._markAsUpdated();
            return this;
        };
        /**
         * Adds the current matrix with a second one
         * @param other defines the matrix to add
         * @returns a new matrix as the addition of the current matrix and the given one
         */
        Matrix.prototype.add = function (other) {
            var result = new Matrix();
            this.addToRef(other, result);
            return result;
        };
        /**
         * Sets the given matrix "result" to the addition of the current matrix and the given one
         * @param other defines the matrix to add
         * @param result defines the target matrix
         * @returns the current matrix
         */
        Matrix.prototype.addToRef = function (other, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = this.m[index] + other.m[index];
            }
            result._markAsUpdated();
            return this;
        };
        /**
         * Adds in place the given matrix to the current matrix
         * @param other defines the second operand
         * @returns the current updated matrix
         */
        Matrix.prototype.addToSelf = function (other) {
            for (var index = 0; index < 16; index++) {
                this.m[index] += other.m[index];
            }
            this._markAsUpdated();
            return this;
        };
        /**
         * Sets the given matrix to the current inverted Matrix
         * @param other defines the target matrix
         * @returns the unmodified current matrix
         */
        Matrix.prototype.invertToRef = function (other) {
            var l1 = this.m[0];
            var l2 = this.m[1];
            var l3 = this.m[2];
            var l4 = this.m[3];
            var l5 = this.m[4];
            var l6 = this.m[5];
            var l7 = this.m[6];
            var l8 = this.m[7];
            var l9 = this.m[8];
            var l10 = this.m[9];
            var l11 = this.m[10];
            var l12 = this.m[11];
            var l13 = this.m[12];
            var l14 = this.m[13];
            var l15 = this.m[14];
            var l16 = this.m[15];
            var l17 = (l11 * l16) - (l12 * l15);
            var l18 = (l10 * l16) - (l12 * l14);
            var l19 = (l10 * l15) - (l11 * l14);
            var l20 = (l9 * l16) - (l12 * l13);
            var l21 = (l9 * l15) - (l11 * l13);
            var l22 = (l9 * l14) - (l10 * l13);
            var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
            var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
            var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
            var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
            var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
            var l28 = (l7 * l16) - (l8 * l15);
            var l29 = (l6 * l16) - (l8 * l14);
            var l30 = (l6 * l15) - (l7 * l14);
            var l31 = (l5 * l16) - (l8 * l13);
            var l32 = (l5 * l15) - (l7 * l13);
            var l33 = (l5 * l14) - (l6 * l13);
            var l34 = (l7 * l12) - (l8 * l11);
            var l35 = (l6 * l12) - (l8 * l10);
            var l36 = (l6 * l11) - (l7 * l10);
            var l37 = (l5 * l12) - (l8 * l9);
            var l38 = (l5 * l11) - (l7 * l9);
            var l39 = (l5 * l10) - (l6 * l9);
            other.m[0] = l23 * l27;
            other.m[4] = l24 * l27;
            other.m[8] = l25 * l27;
            other.m[12] = l26 * l27;
            other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
            other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
            other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
            other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
            other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
            other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
            other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
            other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
            other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
            other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
            other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
            other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
            other._markAsUpdated();
            return this;
        };
        /**
         * Inserts the translation vector (using 3 floats) in the current matrix
         * @param x defines the 1st component of the translation
         * @param y defines the 2nd component of the translation
         * @param z defines the 3rd component of the translation
         * @returns the current updated matrix
         */
        Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
            this.m[12] = x;
            this.m[13] = y;
            this.m[14] = z;
            this._markAsUpdated();
            return this;
        };
        /**
         * Inserts the translation vector in the current matrix
         * @param vector3 defines the translation to insert
         * @returns the current updated matrix
         */
        Matrix.prototype.setTranslation = function (vector3) {
            this.m[12] = vector3.x;
            this.m[13] = vector3.y;
            this.m[14] = vector3.z;
            this._markAsUpdated();
            return this;
        };
        /**
         * Gets the translation value of the current matrix
         * @returns a new Vector3 as the extracted translation from the matrix
         */
        Matrix.prototype.getTranslation = function () {
            return new Vector3(this.m[12], this.m[13], this.m[14]);
        };
        /**
         * Fill a Vector3 with the extracted translation from the matrix
         * @param result defines the Vector3 where to store the translation
         * @returns the current matrix
         */
        Matrix.prototype.getTranslationToRef = function (result) {
            result.x = this.m[12];
            result.y = this.m[13];
            result.z = this.m[14];
            return this;
        };
        /**
         * Remove rotation and scaling part from the matrix
         * @returns the updated matrix
         */
        Matrix.prototype.removeRotationAndScaling = function () {
            this.setRowFromFloats(0, 1, 0, 0, 0);
            this.setRowFromFloats(1, 0, 1, 0, 0);
            this.setRowFromFloats(2, 0, 0, 1, 0);
            return this;
        };
        /**
         * Multiply two matrices
         * @param other defines the second operand
         * @returns a new matrix set with the multiplication result of the current Matrix and the given one
         */
        Matrix.prototype.multiply = function (other) {
            var result = new Matrix();
            this.multiplyToRef(other, result);
            return result;
        };
        /**
         * Copy the current matrix from the given one
         * @param other defines the source matrix
         * @returns the current updated matrix
         */
        Matrix.prototype.copyFrom = function (other) {
            for (var index = 0; index < 16; index++) {
                this.m[index] = other.m[index];
            }
            this._markAsUpdated();
            return this;
        };
        /**
         * Populates the given array from the starting index with the current matrix values
         * @param array defines the target array
         * @param offset defines the offset in the target array where to start storing values
         * @returns the current matrix
         */
        Matrix.prototype.copyToArray = function (array, offset) {
            if (offset === void 0) { offset = 0; }
            for (var index = 0; index < 16; index++) {
                array[offset + index] = this.m[index];
            }
            return this;
        };
        /**
         * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
         * @param other defines the second operand
         * @param result defines the matrix where to store the multiplication
         * @returns the current matrix
         */
        Matrix.prototype.multiplyToRef = function (other, result) {
            this.multiplyToArray(other, result.m, 0);
            result._markAsUpdated();
            return this;
        };
        /**
         * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
         * @param other defines the second operand
         * @param result defines the array where to store the multiplication
         * @param offset defines the offset in the target array where to start storing values
         * @returns the current matrix
         */
        Matrix.prototype.multiplyToArray = function (other, result, offset) {
            var tm0 = this.m[0];
            var tm1 = this.m[1];
            var tm2 = this.m[2];
            var tm3 = this.m[3];
            var tm4 = this.m[4];
            var tm5 = this.m[5];
            var tm6 = this.m[6];
            var tm7 = this.m[7];
            var tm8 = this.m[8];
            var tm9 = this.m[9];
            var tm10 = this.m[10];
            var tm11 = this.m[11];
            var tm12 = this.m[12];
            var tm13 = this.m[13];
            var tm14 = this.m[14];
            var tm15 = this.m[15];
            var om0 = other.m[0];
            var om1 = other.m[1];
            var om2 = other.m[2];
            var om3 = other.m[3];
            var om4 = other.m[4];
            var om5 = other.m[5];
            var om6 = other.m[6];
            var om7 = other.m[7];
            var om8 = other.m[8];
            var om9 = other.m[9];
            var om10 = other.m[10];
            var om11 = other.m[11];
            var om12 = other.m[12];
            var om13 = other.m[13];
            var om14 = other.m[14];
            var om15 = other.m[15];
            result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
            result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
            result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
            result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
            result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
            result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
            result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
            result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
            result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
            result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
            result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
            result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
            result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
            result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
            result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
            result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
            return this;
        };
        /**
         * Check equality between this matrix and a second one
         * @param value defines the second matrix to compare
         * @returns true is the current matrix and the given one values are strictly equal
         */
        Matrix.prototype.equals = function (value) {
            return value &&
                (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
                    this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
                    this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
                    this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
        };
        /**
         * Clone the current matrix
         * @returns a new matrix from the current matrix
         */
        Matrix.prototype.clone = function () {
            return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
        };
        /**
         * Returns the name of the current matrix class
         * @returns the string "Matrix"
         */
        Matrix.prototype.getClassName = function () {
            return "Matrix";
        };
        /**
         * Gets the hash code of the current matrix
         * @returns the hash code
         */
        Matrix.prototype.getHashCode = function () {
            var hash = this.m[0] || 0;
            for (var i = 1; i < 16; i++) {
                hash = (hash * 397) ^ (this.m[i] || 0);
            }
            return hash;
        };
        /**
         * Decomposes the current Matrix into a translation, rotation and scaling components
         * @param scale defines the scale vector3 given as a reference to update
         * @param rotation defines the rotation quaternion given as a reference to update
         * @param translation defines the translation vector3 given as a reference to update
         * @returns true if operation was successful
         */
        Matrix.prototype.decompose = function (scale, rotation, translation) {
            if (translation) {
                translation.x = this.m[12];
                translation.y = this.m[13];
                translation.z = this.m[14];
            }
            scale = scale || MathTmp.Vector3[0];
            scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
            scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
            scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
            if (this.determinant() <= 0) {
                scale.y *= -1;
            }
            if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
                if (rotation) {
                    rotation.x = 0;
                    rotation.y = 0;
                    rotation.z = 0;
                    rotation.w = 1;
                }
                return false;
            }
            if (rotation) {
                Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
                Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
            }
            return true;
        };
        /**
         * Gets specific row of the matrix
         * @param index defines the number of the row to get
         * @returns the index-th row of the current matrix as a new Vector4
         */
        Matrix.prototype.getRow = function (index) {
            if (index < 0 || index > 3) {
                return null;
            }
            var i = index * 4;
            return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
        };
        /**
         * Sets the index-th row of the current matrix to the vector4 values
         * @param index defines the number of the row to set
         * @param row defines the target vector4
         * @returns the updated current matrix
         */
        Matrix.prototype.setRow = function (index, row) {
            if (index < 0 || index > 3) {
                return this;
            }
            var i = index * 4;
            this.m[i + 0] = row.x;
            this.m[i + 1] = row.y;
            this.m[i + 2] = row.z;
            this.m[i + 3] = row.w;
            this._markAsUpdated();
            return this;
        };
        /**
         * Compute the transpose of the matrix
         * @returns the new transposed matrix
         */
        Matrix.prototype.transpose = function () {
            return Matrix.Transpose(this);
        };
        /**
         * Compute the transpose of the matrix and store it in a given matrix
         * @param result defines the target matrix
         * @returns the current matrix
         */
        Matrix.prototype.transposeToRef = function (result) {
            Matrix.TransposeToRef(this, result);
            return this;
        };
        /**
         * Sets the index-th row of the current matrix with the given 4 x float values
         * @param index defines the row index
         * @param x defines the x component to set
         * @param y defines the y component to set
         * @param z defines the z component to set
         * @param w defines the w component to set
         * @returns the updated current matrix
         */
        Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
            if (index < 0 || index > 3) {
                return this;
            }
            var i = index * 4;
            this.m[i + 0] = x;
            this.m[i + 1] = y;
            this.m[i + 2] = z;
            this.m[i + 3] = w;
            this._markAsUpdated();
            return this;
        };
        /**
         * Compute a new matrix set with the current matrix values multiplied by scale (float)
         * @param scale defines the scale factor
         * @returns a new matrix
         */
        Matrix.prototype.scale = function (scale) {
            var result = new Matrix();
            this.scaleToRef(scale, result);
            return result;
        };
        /**
         * Scale the current matrix values by a factor to a given result matrix
         * @param scale defines the scale factor
         * @param result defines the matrix to store the result
         * @returns the current matrix
         */
        Matrix.prototype.scaleToRef = function (scale, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = this.m[index] * scale;
            }
            result._markAsUpdated();
            return this;
        };
        /**
         * Scale the current matrix values by a factor and add the result to a given matrix
         * @param scale defines the scale factor
         * @param result defines the Matrix to store the result
         * @returns the current matrix
         */
        Matrix.prototype.scaleAndAddToRef = function (scale, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] += this.m[index] * scale;
            }
            result._markAsUpdated();
            return this;
        };
        /**
         * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
         * @param ref matrix to store the result
         */
        Matrix.prototype.toNormalMatrix = function (ref) {
            this.invertToRef(ref);
            ref.transpose();
            var m = ref.m;
            Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
        };
        /**
         * Gets only rotation part of the current matrix
         * @returns a new matrix sets to the extracted rotation matrix from the current one
         */
        Matrix.prototype.getRotationMatrix = function () {
            var result = Matrix.Identity();
            this.getRotationMatrixToRef(result);
            return result;
        };
        /**
         * Extracts the rotation matrix from the current one and sets it as the given "result"
         * @param result defines the target matrix to store data to
         * @returns the current matrix
         */
        Matrix.prototype.getRotationMatrixToRef = function (result) {
            var m = this.m;
            var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
            var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
            var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
            if (this.determinant() <= 0) {
                sy *= -1;
            }
            if (sx === 0 || sy === 0 || sz === 0) {
                Matrix.IdentityToRef(result);
            }
            else {
                Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
            }
            return this;
        };
        // Statics
        /**
         * Creates a matrix from an array
         * @param array defines the source array
         * @param offset defines an offset in the source array
         * @returns a new Matrix set from the starting index of the given array
         */
        Matrix.FromArray = function (array, offset) {
            var result = new Matrix();
            if (!offset) {
                offset = 0;
            }
            Matrix.FromArrayToRef(array, offset, result);
            return result;
        };
        /**
         * Copy the content of an array into a given matrix
         * @param array defines the source array
         * @param offset defines an offset in the source array
         * @param result defines the target matrix
         */
        Matrix.FromArrayToRef = function (array, offset, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = array[index + offset];
            }
            result._markAsUpdated();
        };
        /**
         * Stores an array into a matrix after having multiplied each component by a given factor
         * @param array defines the source array
         * @param offset defines the offset in the source array
         * @param scale defines the scaling factor
         * @param result defines the target matrix
         */
        Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = array[index + offset] * scale;
            }
            result._markAsUpdated();
        };
        /**
         * Stores a list of values (16) inside a given matrix
         * @param initialM11 defines 1st value of 1st row
         * @param initialM12 defines 2nd value of 1st row
         * @param initialM13 defines 3rd value of 1st row
         * @param initialM14 defines 4th value of 1st row
         * @param initialM21 defines 1st value of 2nd row
         * @param initialM22 defines 2nd value of 2nd row
         * @param initialM23 defines 3rd value of 2nd row
         * @param initialM24 defines 4th value of 2nd row
         * @param initialM31 defines 1st value of 3rd row
         * @param initialM32 defines 2nd value of 3rd row
         * @param initialM33 defines 3rd value of 3rd row
         * @param initialM34 defines 4th value of 3rd row
         * @param initialM41 defines 1st value of 4th row
         * @param initialM42 defines 2nd value of 4th row
         * @param initialM43 defines 3rd value of 4th row
         * @param initialM44 defines 4th value of 4th row
         * @param result defines the target matrix
         */
        Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
            result.m[0] = initialM11;
            result.m[1] = initialM12;
            result.m[2] = initialM13;
            result.m[3] = initialM14;
            result.m[4] = initialM21;
            result.m[5] = initialM22;
            result.m[6] = initialM23;
            result.m[7] = initialM24;
            result.m[8] = initialM31;
            result.m[9] = initialM32;
            result.m[10] = initialM33;
            result.m[11] = initialM34;
            result.m[12] = initialM41;
            result.m[13] = initialM42;
            result.m[14] = initialM43;
            result.m[15] = initialM44;
            result._markAsUpdated();
        };
        Object.defineProperty(Matrix, "IdentityReadOnly", {
            /**
             * Gets an identity matrix that must not be updated
             */
            get: function () {
                return Matrix._identityReadOnly;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Creates new matrix from a list of values (16)
         * @param initialM11 defines 1st value of 1st row
         * @param initialM12 defines 2nd value of 1st row
         * @param initialM13 defines 3rd value of 1st row
         * @param initialM14 defines 4th value of 1st row
         * @param initialM21 defines 1st value of 2nd row
         * @param initialM22 defines 2nd value of 2nd row
         * @param initialM23 defines 3rd value of 2nd row
         * @param initialM24 defines 4th value of 2nd row
         * @param initialM31 defines 1st value of 3rd row
         * @param initialM32 defines 2nd value of 3rd row
         * @param initialM33 defines 3rd value of 3rd row
         * @param initialM34 defines 4th value of 3rd row
         * @param initialM41 defines 1st value of 4th row
         * @param initialM42 defines 2nd value of 4th row
         * @param initialM43 defines 3rd value of 4th row
         * @param initialM44 defines 4th value of 4th row
         * @returns the new matrix
         */
        Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
            var result = new Matrix();
            result.m[0] = initialM11;
            result.m[1] = initialM12;
            result.m[2] = initialM13;
            result.m[3] = initialM14;
            result.m[4] = initialM21;
            result.m[5] = initialM22;
            result.m[6] = initialM23;
            result.m[7] = initialM24;
            result.m[8] = initialM31;
            result.m[9] = initialM32;
            result.m[10] = initialM33;
            result.m[11] = initialM34;
            result.m[12] = initialM41;
            result.m[13] = initialM42;
            result.m[14] = initialM43;
            result.m[15] = initialM44;
            return result;
        };
        /**
         * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
         * @param scale defines the scale vector3
         * @param rotation defines the rotation quaternion
         * @param translation defines the translation vector3
         * @returns a new matrix
         */
        Matrix.Compose = function (scale, rotation, translation) {
            var result = Matrix.Identity();
            Matrix.ComposeToRef(scale, rotation, translation, result);
            return result;
        };
        /**
         * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
         * @param scale defines the scale vector3
         * @param rotation defines the rotation quaternion
         * @param translation defines the translation vector3
         * @param result defines the target matrix
         */
        Matrix.ComposeToRef = function (scale, rotation, translation, result) {
            Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
            rotation.toRotationMatrix(MathTmp.Matrix[0]);
            MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
            result.setTranslation(translation);
        };
        /**
         * Creates a new identity matrix
         * @returns a new identity matrix
         */
        Matrix.Identity = function () {
            return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
        };
        /**
         * Creates a new identity matrix and stores the result in a given matrix
         * @param result defines the target matrix
         */
        Matrix.IdentityToRef = function (result) {
            Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
        };
        /**
         * Creates a new zero matrix
         * @returns a new zero matrix
         */
        Matrix.Zero = function () {
            return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the X axis
         * @param angle defines the angle (in radians) to use
         * @return the new matrix
         */
        Matrix.RotationX = function (angle) {
            var result = new Matrix();
            Matrix.RotationXToRef(angle, result);
            return result;
        };
        /**
         * Creates a new matrix as the invert of a given matrix
         * @param source defines the source matrix
         * @returns the new matrix
         */
        Matrix.Invert = function (source) {
            var result = new Matrix();
            source.invertToRef(result);
            return result;
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
         * @param angle defines the angle (in radians) to use
         * @param result defines the target matrix
         */
        Matrix.RotationXToRef = function (angle, result) {
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            result.m[0] = 1.0;
            result.m[15] = 1.0;
            result.m[5] = c;
            result.m[10] = c;
            result.m[9] = -s;
            result.m[6] = s;
            result.m[1] = 0.0;
            result.m[2] = 0.0;
            result.m[3] = 0.0;
            result.m[4] = 0.0;
            result.m[7] = 0.0;
            result.m[8] = 0.0;
            result.m[11] = 0.0;
            result.m[12] = 0.0;
            result.m[13] = 0.0;
            result.m[14] = 0.0;
            result._markAsUpdated();
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the Y axis
         * @param angle defines the angle (in radians) to use
         * @return the new matrix
         */
        Matrix.RotationY = function (angle) {
            var result = new Matrix();
            Matrix.RotationYToRef(angle, result);
            return result;
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
         * @param angle defines the angle (in radians) to use
         * @param result defines the target matrix
         */
        Matrix.RotationYToRef = function (angle, result) {
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            result.m[5] = 1.0;
            result.m[15] = 1.0;
            result.m[0] = c;
            result.m[2] = -s;
            result.m[8] = s;
            result.m[10] = c;
            result.m[1] = 0.0;
            result.m[3] = 0.0;
            result.m[4] = 0.0;
            result.m[6] = 0.0;
            result.m[7] = 0.0;
            result.m[9] = 0.0;
            result.m[11] = 0.0;
            result.m[12] = 0.0;
            result.m[13] = 0.0;
            result.m[14] = 0.0;
            result._markAsUpdated();
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the Z axis
         * @param angle defines the angle (in radians) to use
         * @return the new matrix
         */
        Matrix.RotationZ = function (angle) {
            var result = new Matrix();
            Matrix.RotationZToRef(angle, result);
            return result;
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
         * @param angle defines the angle (in radians) to use
         * @param result defines the target matrix
         */
        Matrix.RotationZToRef = function (angle, result) {
            var s = Math.sin(angle);
            var c = Math.cos(angle);
            result.m[10] = 1.0;
            result.m[15] = 1.0;
            result.m[0] = c;
            result.m[1] = s;
            result.m[4] = -s;
            result.m[5] = c;
            result.m[2] = 0.0;
            result.m[3] = 0.0;
            result.m[6] = 0.0;
            result.m[7] = 0.0;
            result.m[8] = 0.0;
            result.m[9] = 0.0;
            result.m[11] = 0.0;
            result.m[12] = 0.0;
            result.m[13] = 0.0;
            result.m[14] = 0.0;
            result._markAsUpdated();
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the given axis
         * @param axis defines the axis to use
         * @param angle defines the angle (in radians) to use
         * @return the new matrix
         */
        Matrix.RotationAxis = function (axis, angle) {
            var result = Matrix.Zero();
            Matrix.RotationAxisToRef(axis, angle, result);
            return result;
        };
        /**
         * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
         * @param axis defines the axis to use
         * @param angle defines the angle (in radians) to use
         * @param result defines the target matrix
         */
        Matrix.RotationAxisToRef = function (axis, angle, result) {
            var s = Math.sin(-angle);
            var c = Math.cos(-angle);
            var c1 = 1 - c;
            axis.normalize();
            result.m[0] = (axis.x * axis.x) * c1 + c;
            result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
            result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
            result.m[3] = 0.0;
            result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
            result.m[5] = (axis.y * axis.y) * c1 + c;
            result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
            result.m[7] = 0.0;
            result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
            result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
            result.m[10] = (axis.z * axis.z) * c1 + c;
            result.m[11] = 0.0;
            result.m[15] = 1.0;
            result._markAsUpdated();
        };
        /**
         * Creates a rotation matrix
         * @param yaw defines the yaw angle in radians (Y axis)
         * @param pitch defines the pitch angle in radians (X axis)
         * @param roll defines the roll angle in radians (X axis)
         * @returns the new rotation matrix
         */
        Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
            var result = new Matrix();
            Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
            return result;
        };
        /**
         * Creates a rotation matrix and stores it in a given matrix
         * @param yaw defines the yaw angle in radians (Y axis)
         * @param pitch defines the pitch angle in radians (X axis)
         * @param roll defines the roll angle in radians (X axis)
         * @param result defines the target matrix
         */
        Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
            Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
            this._tempQuaternion.toRotationMatrix(result);
        };
        /**
         * Creates a scaling matrix
         * @param x defines the scale factor on X axis
         * @param y defines the scale factor on Y axis
         * @param z defines the scale factor on Z axis
         * @returns the new matrix
         */
        Matrix.Scaling = function (x, y, z) {
            var result = Matrix.Zero();
            Matrix.ScalingToRef(x, y, z, result);
            return result;
        };
        /**
         * Creates a scaling matrix and stores it in a given matrix
         * @param x defines the scale factor on X axis
         * @param y defines the scale factor on Y axis
         * @param z defines the scale factor on Z axis
         * @param result defines the target matrix
         */
        Matrix.ScalingToRef = function (x, y, z, result) {
            result.m[0] = x;
            result.m[1] = 0.0;
            result.m[2] = 0.0;
            result.m[3] = 0.0;
            result.m[4] = 0.0;
            result.m[5] = y;
            result.m[6] = 0.0;
            result.m[7] = 0.0;
            result.m[8] = 0.0;
            result.m[9] = 0.0;
            result.m[10] = z;
            result.m[11] = 0.0;
            result.m[12] = 0.0;
            result.m[13] = 0.0;
            result.m[14] = 0.0;
            result.m[15] = 1.0;
            result._markAsUpdated();
        };
        /**
         * Creates a translation matrix
         * @param x defines the translation on X axis
         * @param y defines the translation on Y axis
         * @param z defines the translationon Z axis
         * @returns the new matrix
         */
        Matrix.Translation = function (x, y, z) {
            var result = Matrix.Identity();
            Matrix.TranslationToRef(x, y, z, result);
            return result;
        };
        /**
         * Creates a translation matrix and stores it in a given matrix
         * @param x defines the translation on X axis
         * @param y defines the translation on Y axis
         * @param z defines the translationon Z axis
         * @param result defines the target matrix
         */
        Matrix.TranslationToRef = function (x, y, z, result) {
            Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
        };
        /**
         * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
         * @param startValue defines the start value
         * @param endValue defines the end value
         * @param gradient defines the gradient factor
         * @returns the new matrix
         */
        Matrix.Lerp = function (startValue, endValue, gradient) {
            var result = Matrix.Zero();
            Matrix.LerpToRef(startValue, endValue, gradient, result);
            return result;
        };
        /**
         * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
         * @param startValue defines the start value
         * @param endValue defines the end value
         * @param gradient defines the gradient factor
         * @param result defines the Matrix object where to store data
         */
        Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
            for (var index = 0; index < 16; index++) {
                result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
            }
            result._markAsUpdated();
        };
        /**
         * Builds a new matrix whose values are computed by:
         * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
         * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
         * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
         * @param startValue defines the first matrix
         * @param endValue defines the second matrix
         * @param gradient defines the gradient between the two matrices
         * @returns the new matrix
         */
        Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
            var result = Matrix.Zero();
            Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
            return result;
        };
        /**
         * Update a matrix to values which are computed by:
         * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
         * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
         * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
         * @param startValue defines the first matrix
         * @param endValue defines the second matrix
         * @param gradient defines the gradient between the two matrices
         * @param result defines the target matrix
         */
        Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
            var startScale = MathTmp.Vector3[0];
            var startRotation = MathTmp.Quaternion[0];
            var startTranslation = MathTmp.Vector3[1];
            startValue.decompose(startScale, startRotation, startTranslation);
            var endScale = MathTmp.Vector3[2];
            var endRotation = MathTmp.Quaternion[1];
            var endTranslation = MathTmp.Vector3[3];
            endValue.decompose(endScale, endRotation, endTranslation);
            var resultScale = MathTmp.Vector3[4];
            Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
            var resultRotation = MathTmp.Quaternion[2];
            Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
            var resultTranslation = MathTmp.Vector3[5];
            Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
            Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
        };
        /**
         * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
         * This function works in left handed mode
         * @param eye defines the final position of the entity
         * @param target defines where the entity should look at
         * @param up defines the up vector for the entity
         * @returns the new matrix
         */
        Matrix.LookAtLH = function (eye, target, up) {
            var result = Matrix.Zero();
            Matrix.LookAtLHToRef(eye, target, up, result);
            return result;
        };
        /**
         * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
         * This function works in left handed mode
         * @param eye defines the final position of the entity
         * @param target defines where the entity should look at
         * @param up defines the up vector for the entity
         * @param result defines the target matrix
         */
        Matrix.LookAtLHToRef = function (eye, target, up, result) {
            // Z axis
            target.subtractToRef(eye, this._zAxis);
            this._zAxis.normalize();
            // X axis
            Vector3.CrossToRef(up, this._zAxis, this._xAxis);
            if (this._xAxis.lengthSquared() === 0) {
                this._xAxis.x = 1.0;
            }
            else {
                this._xAxis.normalize();
            }
            // Y axis
            Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
            this._yAxis.normalize();
            // Eye angles
            var ex = -Vector3.Dot(this._xAxis, eye);
            var ey = -Vector3.Dot(this._yAxis, eye);
            var ez = -Vector3.Dot(this._zAxis, eye);
            return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
        };
        /**
         * Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
         * This function works in right handed mode
         * @param eye defines the final position of the entity
         * @param target defines where the entity should look at
         * @param up defines the up vector for the entity
         * @returns the new matrix
         */
        Matrix.LookAtRH = function (eye, target, up) {
            var result = Matrix.Zero();
            Matrix.LookAtRHToRef(eye, target, up, result);
            return result;
        };
        /**
         * Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
         * This function works in right handed mode
         * @param eye defines the final position of the entity
         * @param target defines where the entity should look at
         * @param up defines the up vector for the entity
         * @param result defines the target matrix
         */
        Matrix.LookAtRHToRef = function (eye, target, up, result) {
            // Z axis
            eye.subtractToRef(target, this._zAxis);
            this._zAxis.normalize();
            // X axis
            Vector3.CrossToRef(up, this._zAxis, this._xAxis);
            if (this._xAxis.lengthSquared() === 0) {
                this._xAxis.x = 1.0;
            }
            else {
                this._xAxis.normalize();
            }
            // Y axis
            Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
            this._yAxis.normalize();
            // Eye angles
            var ex = -Vector3.Dot(this._xAxis, eye);
            var ey = -Vector3.Dot(this._yAxis, eye);
            var ez = -Vector3.Dot(this._zAxis, eye);
            return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
        };
        /**
         * Create a left-handed orthographic projection matrix
         * @param width defines the viewport width
         * @param height defines the viewport height
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @returns a new matrix as a left-handed orthographic projection matrix
         */
        Matrix.OrthoLH = function (width, height, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
            return matrix;
        };
        /**
         * Store a left-handed orthographic projection to a given matrix
         * @param width defines the viewport width
         * @param height defines the viewport height
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @param result defines the target matrix
         */
        Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
            var n = znear;
            var f = zfar;
            var a = 2.0 / width;
            var b = 2.0 / height;
            var c = 2.0 / (f - n);
            var d = -(f + n) / (f - n);
            Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
        };
        /**
         * Create a left-handed orthographic projection matrix
         * @param left defines the viewport left coordinate
         * @param right defines the viewport right coordinate
         * @param bottom defines the viewport bottom coordinate
         * @param top defines the viewport top coordinate
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @returns a new matrix as a left-handed orthographic projection matrix
         */
        Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
            return matrix;
        };
        /**
         * Stores a left-handed orthographic projection into a given matrix
         * @param left defines the viewport left coordinate
         * @param right defines the viewport right coordinate
         * @param bottom defines the viewport bottom coordinate
         * @param top defines the viewport top coordinate
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @param result defines the target matrix
         */
        Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
            var n = znear;
            var f = zfar;
            var a = 2.0 / (right - left);
            var b = 2.0 / (top - bottom);
            var c = 2.0 / (f - n);
            var d = -(f + n) / (f - n);
            var i0 = (left + right) / (left - right);
            var i1 = (top + bottom) / (bottom - top);
            Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
        };
        /**
         * Creates a right-handed orthographic projection matrix
         * @param left defines the viewport left coordinate
         * @param right defines the viewport right coordinate
         * @param bottom defines the viewport bottom coordinate
         * @param top defines the viewport top coordinate
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @returns a new matrix as a right-handed orthographic projection matrix
         */
        Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
            return matrix;
        };
        /**
         * Stores a right-handed orthographic projection into a given matrix
         * @param left defines the viewport left coordinate
         * @param right defines the viewport right coordinate
         * @param bottom defines the viewport bottom coordinate
         * @param top defines the viewport top coordinate
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @param result defines the target matrix
         */
        Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
            Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
            result.m[10] *= -1.0;
        };
        /**
         * Creates a left-handed perspective projection matrix
         * @param width defines the viewport width
         * @param height defines the viewport height
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @returns a new matrix as a left-handed perspective projection matrix
         */
        Matrix.PerspectiveLH = function (width, height, znear, zfar) {
            var matrix = Matrix.Zero();
            var n = znear;
            var f = zfar;
            var a = 2.0 * n / width;
            var b = 2.0 * n / height;
            var c = (f + n) / (f - n);
            var d = -2.0 * f * n / (f - n);
            Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
            return matrix;
        };
        /**
         * Creates a left-handed perspective projection matrix
         * @param fov defines the horizontal field of view
         * @param aspect defines the aspect ratio
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @returns a new matrix as a left-handed perspective projection matrix
         */
        Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
            return matrix;
        };
        /**
         * Stores a left-handed perspective projection into a given matrix
         * @param fov defines the horizontal field of view
         * @param aspect defines the aspect ratio
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @param result defines the target matrix
         * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
         */
        Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
            if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
            var n = znear;
            var f = zfar;
            var t = 1.0 / (Math.tan(fov * 0.5));
            var a = isVerticalFovFixed ? (t / aspect) : t;
            var b = isVerticalFovFixed ? t : (t * aspect);
            var c = (f + n) / (f - n);
            var d = -2.0 * f * n / (f - n);
            Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
        };
        /**
         * Creates a right-handed perspective projection matrix
         * @param fov defines the horizontal field of view
         * @param aspect defines the aspect ratio
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @returns a new matrix as a right-handed perspective projection matrix
         */
        Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
            var matrix = Matrix.Zero();
            Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
            return matrix;
        };
        /**
         * Stores a right-handed perspective projection into a given matrix
         * @param fov defines the horizontal field of view
         * @param aspect defines the aspect ratio
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @param result defines the target matrix
         * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
         */
        Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
            //alternatively this could be expressed as:
            //    m = PerspectiveFovLHToRef
            //    m[10] *= -1.0;
            //    m[11] *= -1.0;
            if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
            var n = znear;
            var f = zfar;
            var t = 1.0 / (Math.tan(fov * 0.5));
            var a = isVerticalFovFixed ? (t / aspect) : t;
            var b = isVerticalFovFixed ? t : (t * aspect);
            var c = -(f + n) / (f - n);
            var d = -2 * f * n / (f - n);
            Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
        };
        /**
         * Stores a perspective projection for WebVR info a given matrix
         * @param fov defines the field of view
         * @param znear defines the near clip plane
         * @param zfar defines the far clip plane
         * @param result defines the target matrix
         * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
         */
        Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
            if (rightHanded === void 0) { rightHanded = false; }
            var rightHandedFactor = rightHanded ? -1 : 1;
            var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
            var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
            var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
            var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
            var xScale = 2.0 / (leftTan + rightTan);
            var yScale = 2.0 / (upTan + downTan);
            result.m[0] = xScale;
            result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
            result.m[5] = yScale;
            result.m[6] = result.m[7] = 0.0;
            result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
            result.m[9] = -((upTan - downTan) * yScale * 0.5);
            result.m[10] = -zfar / (znear - zfar);
            result.m[11] = 1.0 * rightHandedFactor;
            result.m[12] = result.m[13] = result.m[15] = 0.0;
            result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
            result._markAsUpdated();
        };
        /**
         * Computes a complete transformation matrix
         * @param viewport defines the viewport to use
         * @param world defines the world matrix
         * @param view defines the view matrix
         * @param projection defines the projection matrix
         * @param zmin defines the near clip plane
         * @param zmax defines the far clip plane
         * @returns the transformation matrix
         */
        Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
            var cw = viewport.width;
            var ch = viewport.height;
            var cx = viewport.x;
            var cy = viewport.y;
            var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
            return world.multiply(view).multiply(projection).multiply(viewportMatrix);
        };
        /**
         * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
         * @param matrix defines the matrix to use
         * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
         */
        Matrix.GetAsMatrix2x2 = function (matrix) {
            return new Float32Array([
                matrix.m[0], matrix.m[1],
                matrix.m[4], matrix.m[5]
            ]);
        };
        /**
         * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
         * @param matrix defines the matrix to use
         * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
         */
        Matrix.GetAsMatrix3x3 = function (matrix) {
            return new Float32Array([
                matrix.m[0], matrix.m[1], matrix.m[2],
                matrix.m[4], matrix.m[5], matrix.m[6],
                matrix.m[8], matrix.m[9], matrix.m[10]
            ]);
        };
        /**
         * Compute the transpose of a given matrix
         * @param matrix defines the matrix to transpose
         * @returns the new matrix
         */
        Matrix.Transpose = function (matrix) {
            var result = new Matrix();
            Matrix.TransposeToRef(matrix, result);
            return result;
        };
        /**
         * Compute the transpose of a matrix and store it in a target matrix
         * @param matrix defines the matrix to transpose
         * @param result defines the target matrix
         */
        Matrix.TransposeToRef = function (matrix, result) {
            result.m[0] = matrix.m[0];
            result.m[1] = matrix.m[4];
            result.m[2] = matrix.m[8];
            result.m[3] = matrix.m[12];
            result.m[4] = matrix.m[1];
            result.m[5] = matrix.m[5];
            result.m[6] = matrix.m[9];
            result.m[7] = matrix.m[13];
            result.m[8] = matrix.m[2];
            result.m[9] = matrix.m[6];
            result.m[10] = matrix.m[10];
            result.m[11] = matrix.m[14];
            result.m[12] = matrix.m[3];
            result.m[13] = matrix.m[7];
            result.m[14] = matrix.m[11];
            result.m[15] = matrix.m[15];
        };
        /**
         * Computes a reflection matrix from a plane
         * @param plane defines the reflection plane
         * @returns a new matrix
         */
        Matrix.Reflection = function (plane) {
            var matrix = new Matrix();
            Matrix.ReflectionToRef(plane, matrix);
            return matrix;
        };
        /**
         * Computes a reflection matrix from a plane
         * @param plane defines the reflection plane
         * @param result defines the target matrix
         */
        Matrix.ReflectionToRef = function (plane, result) {
            plane.normalize();
            var x = plane.normal.x;
            var y = plane.normal.y;
            var z = plane.normal.z;
            var temp = -2 * x;
            var temp2 = -2 * y;
            var temp3 = -2 * z;
            result.m[0] = (temp * x) + 1;
            result.m[1] = temp2 * x;
            result.m[2] = temp3 * x;
            result.m[3] = 0.0;
            result.m[4] = temp * y;
            result.m[5] = (temp2 * y) + 1;
            result.m[6] = temp3 * y;
            result.m[7] = 0.0;
            result.m[8] = temp * z;
            result.m[9] = temp2 * z;
            result.m[10] = (temp3 * z) + 1;
            result.m[11] = 0.0;
            result.m[12] = temp * plane.d;
            result.m[13] = temp2 * plane.d;
            result.m[14] = temp3 * plane.d;
            result.m[15] = 1.0;
            result._markAsUpdated();
        };
        /**
         * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
         * @param xaxis defines the value of the 1st axis
         * @param yaxis defines the value of the 2nd axis
         * @param zaxis defines the value of the 3rd axis
         * @param result defines the target matrix
         */
        Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
            result.m[0] = xaxis.x;
            result.m[1] = xaxis.y;
            result.m[2] = xaxis.z;
            result.m[3] = 0.0;
            result.m[4] = yaxis.x;
            result.m[5] = yaxis.y;
            result.m[6] = yaxis.z;
            result.m[7] = 0.0;
            result.m[8] = zaxis.x;
            result.m[9] = zaxis.y;
            result.m[10] = zaxis.z;
            result.m[11] = 0.0;
            result.m[12] = 0.0;
            result.m[13] = 0.0;
            result.m[14] = 0.0;
            result.m[15] = 1.0;
            result._markAsUpdated();
        };
        /**
         * Creates a rotation matrix from a quaternion and stores it in a target matrix
         * @param quat defines the quaternion to use
         * @param result defines the target matrix
         */
        Matrix.FromQuaternionToRef = function (quat, result) {
            var xx = quat.x * quat.x;
            var yy = quat.y * quat.y;
            var zz = quat.z * quat.z;
            var xy = quat.x * quat.y;
            var zw = quat.z * quat.w;
            var zx = quat.z * quat.x;
            var yw = quat.y * quat.w;
            var yz = quat.y * quat.z;
            var xw = quat.x * quat.w;
            result.m[0] = 1.0 - (2.0 * (yy + zz));
            result.m[1] = 2.0 * (xy + zw);
            result.m[2] = 2.0 * (zx - yw);
            result.m[3] = 0.0;
            result.m[4] = 2.0 * (xy - zw);
            result.m[5] = 1.0 - (2.0 * (zz + xx));
            result.m[6] = 2.0 * (yz + xw);
            result.m[7] = 0.0;
            result.m[8] = 2.0 * (zx + yw);
            result.m[9] = 2.0 * (yz - xw);
            result.m[10] = 1.0 - (2.0 * (yy + xx));
            result.m[11] = 0.0;
            result.m[12] = 0.0;
            result.m[13] = 0.0;
            result.m[14] = 0.0;
            result.m[15] = 1.0;
            result._markAsUpdated();
        };
        Matrix._tempQuaternion = new Quaternion();
        Matrix._xAxis = Vector3.Zero();
        Matrix._yAxis = Vector3.Zero();
        Matrix._zAxis = Vector3.Zero();
        Matrix._updateFlagSeed = 0;
        Matrix._identityReadOnly = Matrix.Identity();
        return Matrix;
    }());
    BABYLON.Matrix = Matrix;
    /**
     * Represens a plane by the equation ax + by + cz + d = 0
     */
    var Plane = /** @class */ (function () {
        /**
         * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
         * @param a a component of the plane
         * @param b b component of the plane
         * @param c c component of the plane
         * @param d d component of the plane
         */
        function Plane(a, b, c, d) {
            this.normal = new Vector3(a, b, c);
            this.d = d;
        }
        /**
         * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
         */
        Plane.prototype.asArray = function () {
            return [this.normal.x, this.normal.y, this.normal.z, this.d];
        };
        // Methods
        /**
         * @returns a new plane copied from the current Plane.
         */
        Plane.prototype.clone = function () {
            return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
        };
        /**
         * @returns the string "Plane".
         */
        Plane.prototype.getClassName = function () {
            return "Plane";
        };
        /**
         * @returns the Plane hash code.
         */
        Plane.prototype.getHashCode = function () {
            var hash = this.normal.getHashCode();
            hash = (hash * 397) ^ (this.d || 0);
            return hash;
        };
        /**
         * Normalize the current Plane in place.
         * @returns the updated Plane.
         */
        Plane.prototype.normalize = function () {
            var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
            var magnitude = 0.0;
            if (norm !== 0) {
                magnitude = 1.0 / norm;
            }
            this.normal.x *= magnitude;
            this.normal.y *= magnitude;
            this.normal.z *= magnitude;
            this.d *= magnitude;
            return this;
        };
        /**
         * Applies a transformation the plane and returns the result
         * @param transformation the transformation matrix to be applied to the plane
         * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
         */
        Plane.prototype.transform = function (transformation) {
            var transposedMatrix = Matrix.Transpose(transformation);
            var x = this.normal.x;
            var y = this.normal.y;
            var z = this.normal.z;
            var d = this.d;
            var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
            var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
            var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
            var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
            return new Plane(normalX, normalY, normalZ, finalD);
        };
        /**
         * Calcualtte the dot product between the point and the plane normal
         * @param point point to calculate the dot product with
         * @returns the dot product (float) of the point coordinates and the plane normal.
         */
        Plane.prototype.dotCoordinate = function (point) {
            return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
        };
        /**
         * Updates the current Plane from the plane defined by the three given points.
         * @param point1 one of the points used to contruct the plane
         * @param point2 one of the points used to contruct the plane
         * @param point3 one of the points used to contruct the plane
         * @returns the updated Plane.
         */
        Plane.prototype.copyFromPoints = function (point1, point2, point3) {
            var x1 = point2.x - point1.x;
            var y1 = point2.y - point1.y;
            var z1 = point2.z - point1.z;
            var x2 = point3.x - point1.x;
            var y2 = point3.y - point1.y;
            var z2 = point3.z - point1.z;
            var yz = (y1 * z2) - (z1 * y2);
            var xz = (z1 * x2) - (x1 * z2);
            var xy = (x1 * y2) - (y1 * x2);
            var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
            var invPyth;
            if (pyth !== 0) {
                invPyth = 1.0 / pyth;
            }
            else {
                invPyth = 0.0;
            }
            this.normal.x = yz * invPyth;
            this.normal.y = xz * invPyth;
            this.normal.z = xy * invPyth;
            this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
            return this;
        };
        /**
         * Checks if the plane is facing a given direction
         * @param direction the direction to check if the plane is facing
         * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
         * @returns True is the vector "direction"  is the same side than the plane normal.
         */
        Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
            var dot = Vector3.Dot(this.normal, direction);
            return (dot <= epsilon);
        };
        /**
         * Calculates the distance to a point
         * @param point point to calculate distance to
         * @returns the signed distance (float) from the given point to the Plane.
         */
        Plane.prototype.signedDistanceTo = function (point) {
            return Vector3.Dot(point, this.normal) + this.d;
        };
        // Statics
        /**
         * Creates a plane from an  array
         * @param array the array to create a plane from
         * @returns a new Plane from the given array.
         */
        Plane.FromArray = function (array) {
            return new Plane(array[0], array[1], array[2], array[3]);
        };
        /**
         * Creates a plane from three points
         * @param point1 point used to create the plane
         * @param point2 point used to create the plane
         * @param point3 point used to create the plane
         * @returns a new Plane defined by the three given points.
         */
        Plane.FromPoints = function (point1, point2, point3) {
            var result = new Plane(0.0, 0.0, 0.0, 0.0);
            result.copyFromPoints(point1, point2, point3);
            return result;
        };
        /**
         * Creates a plane from an origin point and a normal
         * @param origin origin of the plane to be constructed
         * @param normal normal of the plane to be constructed
         * @returns a new Plane the normal vector to this plane at the given origin point.
         * Note : the vector "normal" is updated because normalized.
         */
        Plane.FromPositionAndNormal = function (origin, normal) {
            var result = new Plane(0.0, 0.0, 0.0, 0.0);
            normal.normalize();
            result.normal = normal;
            result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
            return result;
        };
        /**
         * Calculates the distance from a plane and a point
         * @param origin origin of the plane to be constructed
         * @param normal normal of the plane to be constructed
         * @param point point to calculate distance to
         * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
         */
        Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
            var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
            return Vector3.Dot(point, normal) + d;
        };
        return Plane;
    }());
    BABYLON.Plane = Plane;
    /**
     * Class used to represent a viewport on screen
     */
    var Viewport = /** @class */ (function () {
        /**
         * Creates a Viewport object located at (x, y) and sized (width, height)
         * @param x defines viewport left coordinate
         * @param y defines viewport top coordinate
         * @param width defines the viewport width
         * @param height defines the viewport height
         */
        function Viewport(
        /** viewport left coordinate */
        x, 
        /** viewport top coordinate */
        y, 
        /**viewport width */
        width, 
        /** viewport height */
        height) {
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
        /**
         * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
         * @param renderWidthOrEngine defines either an engine or the rendering width
         * @param renderHeight defines the rendering height
         * @returns a new Viewport
         */
        Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
            if (renderWidthOrEngine.getRenderWidth) {
                var engine = renderWidthOrEngine;
                return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            }
            var renderWidth = renderWidthOrEngine;
            return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
        };
        /**
         * Returns a new Viewport copied from the current one
         * @returns a new Viewport
         */
        Viewport.prototype.clone = function () {
            return new Viewport(this.x, this.y, this.width, this.height);
        };
        return Viewport;
    }());
    BABYLON.Viewport = Viewport;
    /**
     * Reprasents a camera frustum
     */
    var Frustum = /** @class */ (function () {
        function Frustum() {
        }
        /**
         * Gets the planes representing the frustum
         * @param transform matrix to be applied to the returned planes
         * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
         */
        Frustum.GetPlanes = function (transform) {
            var frustumPlanes = [];
            for (var index = 0; index < 6; index++) {
                frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
            }
            Frustum.GetPlanesToRef(transform, frustumPlanes);
            return frustumPlanes;
        };
        /**
         * Gets the near frustum plane transformed by the transform matrix
         * @param transform transformation matrix to be applied to the resulting frustum plane
         * @param frustumPlane the resuling frustum plane
         */
        Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
            frustumPlane.normal.x = transform.m[3] + transform.m[2];
            frustumPlane.normal.y = transform.m[7] + transform.m[6];
            frustumPlane.normal.z = transform.m[11] + transform.m[10];
            frustumPlane.d = transform.m[15] + transform.m[14];
            frustumPlane.normalize();
        };
        /**
         * Gets the far frustum plane transformed by the transform matrix
         * @param transform transformation matrix to be applied to the resulting frustum plane
         * @param frustumPlane the resuling frustum plane
         */
        Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
            frustumPlane.normal.x = transform.m[3] - transform.m[2];
            frustumPlane.normal.y = transform.m[7] - transform.m[6];
            frustumPlane.normal.z = transform.m[11] - transform.m[10];
            frustumPlane.d = transform.m[15] - transform.m[14];
            frustumPlane.normalize();
        };
        /**
         * Gets the left frustum plane transformed by the transform matrix
         * @param transform transformation matrix to be applied to the resulting frustum plane
         * @param frustumPlane the resuling frustum plane
         */
        Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
            frustumPlane.normal.x = transform.m[3] + transform.m[0];
            frustumPlane.normal.y = transform.m[7] + transform.m[4];
            frustumPlane.normal.z = transform.m[11] + transform.m[8];
            frustumPlane.d = transform.m[15] + transform.m[12];
            frustumPlane.normalize();
        };
        /**
         * Gets the right frustum plane transformed by the transform matrix
         * @param transform transformation matrix to be applied to the resulting frustum plane
         * @param frustumPlane the resuling frustum plane
         */
        Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
            frustumPlane.normal.x = transform.m[3] - transform.m[0];
            frustumPlane.normal.y = transform.m[7] - transform.m[4];
            frustumPlane.normal.z = transform.m[11] - transform.m[8];
            frustumPlane.d = transform.m[15] - transform.m[12];
            frustumPlane.normalize();
        };
        /**
         * Gets the top frustum plane transformed by the transform matrix
         * @param transform transformation matrix to be applied to the resulting frustum plane
         * @param frustumPlane the resuling frustum plane
         */
        Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
            frustumPlane.normal.x = transform.m[3] - transform.m[1];
            frustumPlane.normal.y = transform.m[7] - transform.m[5];
            frustumPlane.normal.z = transform.m[11] - transform.m[9];
            frustumPlane.d = transform.m[15] - transform.m[13];
            frustumPlane.normalize();
        };
        /**
         * Gets the bottom frustum plane transformed by the transform matrix
         * @param transform transformation matrix to be applied to the resulting frustum plane
         * @param frustumPlane the resuling frustum plane
         */
        Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
            frustumPlane.normal.x = transform.m[3] + transform.m[1];
            frustumPlane.normal.y = transform.m[7] + transform.m[5];
            frustumPlane.normal.z = transform.m[11] + transform.m[9];
            frustumPlane.d = transform.m[15] + transform.m[13];
            frustumPlane.normalize();
        };
        /**
         * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
         * @param transform transformation matrix to be applied to the resulting frustum planes
         * @param frustumPlanes the resuling frustum planes
         */
        Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
            // Near
            Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
            // Far
            Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
            // Left
            Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
            // Right
            Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
            // Top
            Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
            // Bottom
            Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
        };
        return Frustum;
    }());
    BABYLON.Frustum = Frustum;
    /** Defines supported spaces */
    var Space;
    (function (Space) {
        /** Local (object) space */
        Space[Space["LOCAL"] = 0] = "LOCAL";
        /** World space */
        Space[Space["WORLD"] = 1] = "WORLD";
        /** Bone space */
        Space[Space["BONE"] = 2] = "BONE";
    })(Space = BABYLON.Space || (BABYLON.Space = {}));
    /** Defines the 3 main axes */
    var Axis = /** @class */ (function () {
        function Axis() {
        }
        /** X axis */
        Axis.X = new Vector3(1.0, 0.0, 0.0);
        /** Y axis */
        Axis.Y = new Vector3(0.0, 1.0, 0.0);
        /** Z axis */
        Axis.Z = new Vector3(0.0, 0.0, 1.0);
        return Axis;
    }());
    BABYLON.Axis = Axis;
    /** Class used to represent a Bezier curve */
    var BezierCurve = /** @class */ (function () {
        function BezierCurve() {
        }
        /**
         * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
         * @param t defines the time
         * @param x1 defines the left coordinate on X axis
         * @param y1 defines the left coordinate on Y axis
         * @param x2 defines the right coordinate on X axis
         * @param y2 defines the right coordinate on Y axis
         * @returns the interpolated value
         */
        BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
            // Extract X (which is equal to time here)
            var f0 = 1 - 3 * x2 + 3 * x1;
            var f1 = 3 * x2 - 6 * x1;
            var f2 = 3 * x1;
            var refinedT = t;
            for (var i = 0; i < 5; i++) {
                var refinedT2 = refinedT * refinedT;
                var refinedT3 = refinedT2 * refinedT;
                var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
                var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
                refinedT -= (x - t) * slope;
                refinedT = Math.min(1, Math.max(0, refinedT));
            }
            // Resolve cubic bezier for the given x
            return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
                3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
                Math.pow(refinedT, 3);
        };
        return BezierCurve;
    }());
    BABYLON.BezierCurve = BezierCurve;
    /**
     * Defines potential orientation for back face culling
     */
    var Orientation;
    (function (Orientation) {
        /**
         * Clockwise
         */
        Orientation[Orientation["CW"] = 0] = "CW";
        /** Counter clockwise */
        Orientation[Orientation["CCW"] = 1] = "CCW";
    })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
    /**
     * Defines angle representation
     */
    var Angle = /** @class */ (function () {
        /**
         * Creates an Angle object of "radians" radians (float).
         */
        function Angle(radians) {
            this._radians = radians;
            if (this._radians < 0.0) {
                this._radians += (2.0 * Math.PI);
            }
        }
        /**
         * Get value in degrees
         * @returns the Angle value in degrees (float)
         */
        Angle.prototype.degrees = function () {
            return this._radians * 180.0 / Math.PI;
        };
        /**
         * Get value in radians
         * @returns the Angle value in radians (float)
         */
        Angle.prototype.radians = function () {
            return this._radians;
        };
        /**
         * Gets a new Angle object valued with the angle value in radians between the two given vectors
         * @param a defines first vector
         * @param b defines second vector
         * @returns a new Angle
         */
        Angle.BetweenTwoPoints = function (a, b) {
            var delta = b.subtract(a);
            var theta = Math.atan2(delta.y, delta.x);
            return new Angle(theta);
        };
        /**
         * Gets a new Angle object from the given float in radians
         * @param radians defines the angle value in radians
         * @returns a new Angle
         */
        Angle.FromRadians = function (radians) {
            return new Angle(radians);
        };
        /**
         * Gets a new Angle object from the given float in degrees
         * @param degrees defines the angle value in degrees
         * @returns a new Angle
         */
        Angle.FromDegrees = function (degrees) {
            return new Angle(degrees * Math.PI / 180.0);
        };
        return Angle;
    }());
    BABYLON.Angle = Angle;
    /**
     * This represents an arc in a 2d space.
     */
    var Arc2 = /** @class */ (function () {
        /**
         * Creates an Arc object from the three given points : start, middle and end.
         * @param startPoint Defines the start point of the arc
         * @param midPoint Defines the midlle point of the arc
         * @param endPoint Defines the end point of the arc
         */
        function Arc2(
        /** Defines the start point of the arc */
        startPoint, 
        /** Defines the mid point of the arc */
        midPoint, 
        /** Defines the end point of the arc */
        endPoint) {
            this.startPoint = startPoint;
            this.midPoint = midPoint;
            this.endPoint = endPoint;
            var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
            var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
            var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
            var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
            this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
            this.radius = this.centerPoint.subtract(this.startPoint).length();
            this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
            var a1 = this.startAngle.degrees();
            var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
            var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
            // angles correction
            if (a2 - a1 > +180.0) {
                a2 -= 360.0;
            }
            if (a2 - a1 < -180.0) {
                a2 += 360.0;
            }
            if (a3 - a2 > +180.0) {
                a3 -= 360.0;
            }
            if (a3 - a2 < -180.0) {
                a3 += 360.0;
            }
            this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
            this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
        }
        return Arc2;
    }());
    BABYLON.Arc2 = Arc2;
    /**
     * Represents a 2D path made up of multiple 2D points
     */
    var Path2 = /** @class */ (function () {
        /**
         * Creates a Path2 object from the starting 2D coordinates x and y.
         * @param x the starting points x value
         * @param y the starting points y value
         */
        function Path2(x, y) {
            this._points = new Array();
            this._length = 0.0;
            /**
             * If the path start and end point are the same
             */
            this.closed = false;
            this._points.push(new Vector2(x, y));
        }
        /**
         * Adds a new segment until the given coordinates (x, y) to the current Path2.
         * @param x the added points x value
         * @param y the added points y value
         * @returns the updated Path2.
         */
        Path2.prototype.addLineTo = function (x, y) {
            if (this.closed) {
                return this;
            }
            var newPoint = new Vector2(x, y);
            var previousPoint = this._points[this._points.length - 1];
            this._points.push(newPoint);
            this._length += newPoint.subtract(previousPoint).length();
            return this;
        };
        /**
         * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
         * @param midX middle point x value
         * @param midY middle point y value
         * @param endX end point x value
         * @param endY end point y value
         * @param numberOfSegments (default: 36)
         * @returns the updated Path2.
         */
        Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
            if (numberOfSegments === void 0) { numberOfSegments = 36; }
            if (this.closed) {
                return this;
            }
            var startPoint = this._points[this._points.length - 1];
            var midPoint = new Vector2(midX, midY);
            var endPoint = new Vector2(endX, endY);
            var arc = new Arc2(startPoint, midPoint, endPoint);
            var increment = arc.angle.radians() / numberOfSegments;
            if (arc.orientation === Orientation.CW) {
                increment *= -1;
            }
            var currentAngle = arc.startAngle.radians() + increment;
            for (var i = 0; i < numberOfSegments; i++) {
                var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
                var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
                this.addLineTo(x, y);
                currentAngle += increment;
            }
            return this;
        };
        /**
         * Closes the Path2.
         * @returns the Path2.
         */
        Path2.prototype.close = function () {
            this.closed = true;
            return this;
        };
        /**
         * Gets the sum of the distance between each sequential point in the path
         * @returns the Path2 total length (float).
         */
        Path2.prototype.length = function () {
            var result = this._length;
            if (!this.closed) {
                var lastPoint = this._points[this._points.length - 1];
                var firstPoint = this._points[0];
                result += (firstPoint.subtract(lastPoint).length());
            }
            return result;
        };
        /**
         * Gets the points which construct the path
         * @returns the Path2 internal array of points.
         */
        Path2.prototype.getPoints = function () {
            return this._points;
        };
        /**
         * Retreives the point at the distance aways from the starting point
         * @param normalizedLengthPosition the length along the path to retreive the point from
         * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
         */
        Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
            if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
                return Vector2.Zero();
            }
            var lengthPosition = normalizedLengthPosition * this.length();
            var previousOffset = 0;
            for (var i = 0; i < this._points.length; i++) {
                var j = (i + 1) % this._points.length;
                var a = this._points[i];
                var b = this._points[j];
                var bToA = b.subtract(a);
                var nextOffset = (bToA.length() + previousOffset);
                if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
                    var dir = bToA.normalize();
                    var localOffset = lengthPosition - previousOffset;
                    return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
                }
                previousOffset = nextOffset;
            }
            return Vector2.Zero();
        };
        /**
         * Creates a new path starting from an x and y position
         * @param x starting x value
         * @param y starting y value
         * @returns a new Path2 starting at the coordinates (x, y).
         */
        Path2.StartingAt = function (x, y) {
            return new Path2(x, y);
        };
        return Path2;
    }());
    BABYLON.Path2 = Path2;
    /**
     * Represents a 3D path made up of multiple 3D points
     */
    var Path3D = /** @class */ (function () {
        /**
        * new Path3D(path, normal, raw)
        * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
        * please read the description in the tutorial :  http://doc.babylonjs.com/tutorials/How_to_use_Path3D
        * @param path an array of Vector3, the curve axis of the Path3D
        * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
        * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
        */
        function Path3D(
        /**
         * an array of Vector3, the curve axis of the Path3D
         */
        path, firstNormal, raw) {
            if (firstNormal === void 0) { firstNormal = null; }
            this.path = path;
            this._curve = new Array();
            this._distances = new Array();
            this._tangents = new Array();
            this._normals = new Array();
            this._binormals = new Array();
            for (var p = 0; p < path.length; p++) {
                this._curve[p] = path[p].clone(); // hard copy
            }
            this._raw = raw || false;
            this._compute(firstNormal);
        }
        /**
         * Returns the Path3D array of successive Vector3 designing its curve.
         * @returns the Path3D array of successive Vector3 designing its curve.
         */
        Path3D.prototype.getCurve = function () {
            return this._curve;
        };
        /**
         * Returns an array populated with tangent vectors on each Path3D curve point.
         * @returns an array populated with tangent vectors on each Path3D curve point.
         */
        Path3D.prototype.getTangents = function () {
            return this._tangents;
        };
        /**
         * Returns an array populated with normal vectors on each Path3D curve point.
         * @returns an array populated with normal vectors on each Path3D curve point.
         */
        Path3D.prototype.getNormals = function () {
            return this._normals;
        };
        /**
         * Returns an array populated with binormal vectors on each Path3D curve point.
         * @returns an array populated with binormal vectors on each Path3D curve point.
         */
        Path3D.prototype.getBinormals = function () {
            return this._binormals;
        };
        /**
         * Returns an array populated with distances (float) of the i-th point from the first curve point.
         * @returns an array populated with distances (float) of the i-th point from the first curve point.
         */
        Path3D.prototype.getDistances = function () {
            return this._distances;
        };
        /**
         * Forces the Path3D tangent, normal, binormal and distance recomputation.
         * @param path path which all values are copied into the curves points
         * @param firstNormal which should be projected onto the curve
         * @returns the same object updated.
         */
        Path3D.prototype.update = function (path, firstNormal) {
            if (firstNormal === void 0) { firstNormal = null; }
            for (var p = 0; p < path.length; p++) {
                this._curve[p].x = path[p].x;
                this._curve[p].y = path[p].y;
                this._curve[p].z = path[p].z;
            }
            this._compute(firstNormal);
            return this;
        };
        // private function compute() : computes tangents, normals and binormals
        Path3D.prototype._compute = function (firstNormal) {
            var l = this._curve.length;
            // first and last tangents
            this._tangents[0] = this._getFirstNonNullVector(0);
            if (!this._raw) {
                this._tangents[0].normalize();
            }
            this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
            if (!this._raw) {
                this._tangents[l - 1].normalize();
            }
            // normals and binormals at first point : arbitrary vector with _normalVector()
            var tg0 = this._tangents[0];
            var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
            this._normals[0] = pp0;
            if (!this._raw) {
                this._normals[0].normalize();
            }
            this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
            if (!this._raw) {
                this._binormals[0].normalize();
            }
            this._distances[0] = 0.0;
            // normals and binormals : next points
            var prev; // previous vector (segment)
            var cur; // current vector (segment)
            var curTang; // current tangent
            // previous normal
            var prevBinor; // previous binormal
            for (var i = 1; i < l; i++) {
                // tangents
                prev = this._getLastNonNullVector(i);
                if (i < l - 1) {
                    cur = this._getFirstNonNullVector(i);
                    this._tangents[i] = prev.add(cur);
                    this._tangents[i].normalize();
                }
                this._distances[i] = this._distances[i - 1] + prev.length();
                // normals and binormals
                // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
                curTang = this._tangents[i];
                prevBinor = this._binormals[i - 1];
                this._normals[i] = Vector3.Cross(prevBinor, curTang);
                if (!this._raw) {
                    this._normals[i].normalize();
                }
                this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
                if (!this._raw) {
                    this._binormals[i].normalize();
                }
            }
        };
        // private function getFirstNonNullVector(index)
        // returns the first non null vector from index : curve[index + N].subtract(curve[index])
        Path3D.prototype._getFirstNonNullVector = function (index) {
            var i = 1;
            var nNVector = this._curve[index + i].subtract(this._curve[index]);
            while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
                i++;
                nNVector = this._curve[index + i].subtract(this._curve[index]);
            }
            return nNVector;
        };
        // private function getLastNonNullVector(index)
        // returns the last non null vector from index : curve[index].subtract(curve[index - N])
        Path3D.prototype._getLastNonNullVector = function (index) {
            var i = 1;
            var nLVector = this._curve[index].subtract(this._curve[index - i]);
            while (nLVector.length() === 0 && index > i + 1) {
                i++;
                nLVector = this._curve[index].subtract(this._curve[index - i]);
            }
            return nLVector;
        };
        // private function normalVector(v0, vt, va) :
        // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
        // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
        Path3D.prototype._normalVector = function (v0, vt, va) {
            var normal0;
            var tgl = vt.length();
            if (tgl === 0.0) {
                tgl = 1.0;
            }
            if (va === undefined || va === null) {
                var point;
                if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
                    point = new Vector3(0.0, -1.0, 0.0);
                }
                else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
                    point = new Vector3(1.0, 0.0, 0.0);
                }
                else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
                    point = new Vector3(0.0, 0.0, 1.0);
                }
                else {
                    point = Vector3.Zero();
                }
                normal0 = Vector3.Cross(vt, point);
            }
            else {
                normal0 = Vector3.Cross(vt, va);
                Vector3.CrossToRef(normal0, vt, normal0);
            }
            normal0.normalize();
            return normal0;
        };
        return Path3D;
    }());
    BABYLON.Path3D = Path3D;
    /**
     * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
     * A Curve3 is designed from a series of successive Vector3.
     * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
     */
    var Curve3 = /** @class */ (function () {
        /**
         * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
         * A Curve3 is designed from a series of successive Vector3.
         * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
         * @param points points which make up the curve
         */
        function Curve3(points) {
            this._length = 0.0;
            this._points = points;
            this._length = this._computeLength(points);
        }
        /**
         * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
         * @param v0 (Vector3) the origin point of the Quadratic Bezier
         * @param v1 (Vector3) the control point
         * @param v2 (Vector3) the end point of the Quadratic Bezier
         * @param nbPoints (integer) the wanted number of points in the curve
         * @returns the created Curve3
         */
        Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
            nbPoints = nbPoints > 2 ? nbPoints : 3;
            var bez = new Array();
            var equation = function (t, val0, val1, val2) {
                var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
                return res;
            };
            for (var i = 0; i <= nbPoints; i++) {
                bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
            }
            return new Curve3(bez);
        };
        /**
         * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
         * @param v0 (Vector3) the origin point of the Cubic Bezier
         * @param v1 (Vector3) the first control point
         * @param v2 (Vector3) the second control point
         * @param v3 (Vector3) the end point of the Cubic Bezier
         * @param nbPoints (integer) the wanted number of points in the curve
         * @returns the created Curve3
         */
        Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
            nbPoints = nbPoints > 3 ? nbPoints : 4;
            var bez = new Array();
            var equation = function (t, val0, val1, val2, val3) {
                var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
                return res;
            };
            for (var i = 0; i <= nbPoints; i++) {
                bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
            }
            return new Curve3(bez);
        };
        /**
         * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
         * @param p1 (Vector3) the origin point of the Hermite Spline
         * @param t1 (Vector3) the tangent vector at the origin point
         * @param p2 (Vector3) the end point of the Hermite Spline
         * @param t2 (Vector3) the tangent vector at the end point
         * @param nbPoints (integer) the wanted number of points in the curve
         * @returns the created Curve3
         */
        Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
            var hermite = new Array();
            var step = 1.0 / nbPoints;
            for (var i = 0; i <= nbPoints; i++) {
                hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
            }
            return new Curve3(hermite);
        };
        /**
         * Returns a Curve3 object along a CatmullRom Spline curve :
         * @param points (array of Vector3) the points the spline must pass through. At least, four points required
         * @param nbPoints (integer) the wanted number of points between each curve control points
         * @param closed (boolean) optional with default false, when true forms a closed loop from the points
         * @returns the created Curve3
         */
        Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
            var catmullRom = new Array();
            var step = 1.0 / nbPoints;
            var amount = 0.0;
            if (closed) {
                var pointsCount = points.length;
                for (var i = 0; i < pointsCount; i++) {
                    amount = 0;
                    for (var c = 0; c < nbPoints; c++) {
                        catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
                        amount += step;
                    }
                }
                catmullRom.push(catmullRom[0]);
            }
            else {
                var totalPoints = new Array();
                totalPoints.push(points[0].clone());
                Array.prototype.push.apply(totalPoints, points);
                totalPoints.push(points[points.length - 1].clone());
                for (var i = 0; i < totalPoints.length - 3; i++) {
                    amount = 0;
                    for (var c = 0; c < nbPoints; c++) {
                        catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
                        amount += step;
                    }
                }
                i--;
                catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
            }
            return new Curve3(catmullRom);
        };
        /**
         * @returns the Curve3 stored array of successive Vector3
         */
        Curve3.prototype.getPoints = function () {
            return this._points;
        };
        /**
         * @returns the computed length (float) of the curve.
         */
        Curve3.prototype.length = function () {
            return this._length;
        };
        /**
         * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
         * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
         * curveA and curveB keep unchanged.
         * @param curve the curve to continue from this curve
         * @returns the newly constructed curve
         */
        Curve3.prototype.continue = function (curve) {
            var lastPoint = this._points[this._points.length - 1];
            var continuedPoints = this._points.slice();
            var curvePoints = curve.getPoints();
            for (var i = 1; i < curvePoints.length; i++) {
                continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
            }
            var continuedCurve = new Curve3(continuedPoints);
            return continuedCurve;
        };
        Curve3.prototype._computeLength = function (path) {
            var l = 0;
            for (var i = 1; i < path.length; i++) {
                l += (path[i].subtract(path[i - 1])).length();
            }
            return l;
        };
        return Curve3;
    }());
    BABYLON.Curve3 = Curve3;
    // Vertex formats
    /**
     * Contains position and normal vectors for a vertex
     */
    var PositionNormalVertex = /** @class */ (function () {
        /**
         * Creates a PositionNormalVertex
         * @param position the position of the vertex (defaut: 0,0,0)
         * @param normal the normal of the vertex (defaut: 0,1,0)
         */
        function PositionNormalVertex(
        /** the position of the vertex (defaut: 0,0,0) */
        position, 
        /** the normal of the vertex (defaut: 0,1,0) */
        normal) {
            if (position === void 0) { position = Vector3.Zero(); }
            if (normal === void 0) { normal = Vector3.Up(); }
            this.position = position;
            this.normal = normal;
        }
        /**
         * Clones the PositionNormalVertex
         * @returns the cloned PositionNormalVertex
         */
        PositionNormalVertex.prototype.clone = function () {
            return new PositionNormalVertex(this.position.clone(), this.normal.clone());
        };
        return PositionNormalVertex;
    }());
    BABYLON.PositionNormalVertex = PositionNormalVertex;
    /**
     * Contains position, normal and uv vectors for a vertex
     */
    var PositionNormalTextureVertex = /** @class */ (function () {
        /**
         * Creates a PositionNormalTextureVertex
         * @param position the position of the vertex (defaut: 0,0,0)
         * @param normal the normal of the vertex (defaut: 0,1,0)
         * @param uv the uv of the vertex (default: 0,0)
         */
        function PositionNormalTextureVertex(
        /** the position of the vertex (defaut: 0,0,0) */
        position, 
        /** the normal of the vertex (defaut: 0,1,0) */
        normal, 
        /** the uv of the vertex (default: 0,0) */
        uv) {
            if (position === void 0) { position = Vector3.Zero(); }
            if (normal === void 0) { normal = Vector3.Up(); }
            if (uv === void 0) { uv = Vector2.Zero(); }
            this.position = position;
            this.normal = normal;
            this.uv = uv;
        }
        /**
         * Clones the PositionNormalTextureVertex
         * @returns the cloned PositionNormalTextureVertex
         */
        PositionNormalTextureVertex.prototype.clone = function () {
            return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
        };
        return PositionNormalTextureVertex;
    }());
    BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
    // Temporary pre-allocated objects for engine internal use
    // usage in any internal function :
    // var tmp = Tmp.Vector3[0];   <= gets access to the first pre-created Vector3
    // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
    /**
     * @hidden
     */
    var Tmp = /** @class */ (function () {
        function Tmp() {
        }
        Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
        Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
        Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
        Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
            Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
        Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
        Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
        Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
            Matrix.Zero(), Matrix.Zero(),
            Matrix.Zero(), Matrix.Zero(),
            Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
        return Tmp;
    }());
    BABYLON.Tmp = Tmp;
    /**
     * @hidden
     * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
     */
    var MathTmp = /** @class */ (function () {
        function MathTmp() {
        }
        MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
        MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
        MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
        return MathTmp;
    }());
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.math.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Scalar computation library
     */
    var Scalar = /** @class */ (function () {
        function Scalar() {
        }
        /**
         * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
         * @param a number
         * @param b number
         * @param epsilon (default = 1.401298E-45)
         * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
         */
        Scalar.WithinEpsilon = function (a, b, epsilon) {
            if (epsilon === void 0) { epsilon = 1.401298E-45; }
            var num = a - b;
            return -epsilon <= num && num <= epsilon;
        };
        /**
         * Returns a string : the upper case translation of the number i to hexadecimal.
         * @param i number
         * @returns the upper case translation of the number i to hexadecimal.
         */
        Scalar.ToHex = function (i) {
            var str = i.toString(16);
            if (i <= 15) {
                return ("0" + str).toUpperCase();
            }
            return str.toUpperCase();
        };
        /**
         * Returns -1 if value is negative and +1 is value is positive.
         * @param value the value
         * @returns the value itself if it's equal to zero.
         */
        Scalar.Sign = function (value) {
            value = +value; // convert to a number
            if (value === 0 || isNaN(value)) {
                return value;
            }
            return value > 0 ? 1 : -1;
        };
        /**
         * Returns the value itself if it's between min and max.
         * Returns min if the value is lower than min.
         * Returns max if the value is greater than max.
         * @param value the value to clmap
         * @param min the min value to clamp to (default: 0)
         * @param max the max value to clamp to (default: 1)
         * @returns the clamped value
         */
        Scalar.Clamp = function (value, min, max) {
            if (min === void 0) { min = 0; }
            if (max === void 0) { max = 1; }
            return Math.min(max, Math.max(min, value));
        };
        /**
         * the log2 of value.
         * @param value the value to compute log2 of
         * @returns the log2 of value.
         */
        Scalar.Log2 = function (value) {
            return Math.log(value) * Math.LOG2E;
        };
        /**
        * Loops the value, so that it is never larger than length and never smaller than 0.
        *
        * This is similar to the modulo operator but it works with floating point numbers.
        * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
        * With t = 5 and length = 2.5, the result would be 0.0.
        * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
        * @param value the value
        * @param length the length
        * @returns the looped value
        */
        Scalar.Repeat = function (value, length) {
            return value - Math.floor(value / length) * length;
        };
        /**
         * Normalize the value between 0.0 and 1.0 using min and max values
         * @param value value to normalize
         * @param min max to normalize between
         * @param max min to normalize between
         * @returns the normalized value
         */
        Scalar.Normalize = function (value, min, max) {
            return (value - min) / (max - min);
        };
        /**
        * Denormalize the value from 0.0 and 1.0 using min and max values
        * @param normalized value to denormalize
        * @param min max to denormalize between
        * @param max min to denormalize between
        * @returns the denormalized value
        */
        Scalar.Denormalize = function (normalized, min, max) {
            return (normalized * (max - min) + min);
        };
        /**
        * Calculates the shortest difference between two given angles given in degrees.
        * @param current current angle in degrees
        * @param target target angle in degrees
        * @returns the delta
        */
        Scalar.DeltaAngle = function (current, target) {
            var num = Scalar.Repeat(target - current, 360.0);
            if (num > 180.0) {
                num -= 360.0;
            }
            return num;
        };
        /**
        * PingPongs the value t, so that it is never larger than length and never smaller than 0.
        * @param tx value
        * @param length length
        * @returns The returned value will move back and forth between 0 and length
        */
        Scalar.PingPong = function (tx, length) {
            var t = Scalar.Repeat(tx, length * 2.0);
            return length - Math.abs(t - length);
        };
        /**
        * Interpolates between min and max with smoothing at the limits.
        *
        * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
        * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
        * @param from from
        * @param to to
        * @param tx value
        * @returns the smooth stepped value
        */
        Scalar.SmoothStep = function (from, to, tx) {
            var t = Scalar.Clamp(tx);
            t = -2.0 * t * t * t + 3.0 * t * t;
            return to * t + from * (1.0 - t);
        };
        /**
        * Moves a value current towards target.
        *
        * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
        * Negative values of maxDelta pushes the value away from target.
        * @param current current value
        * @param target target value
        * @param maxDelta max distance to move
        * @returns resulting value
        */
        Scalar.MoveTowards = function (current, target, maxDelta) {
            var result = 0;
            if (Math.abs(target - current) <= maxDelta) {
                result = target;
            }
            else {
                result = current + Scalar.Sign(target - current) * maxDelta;
            }
            return result;
        };
        /**
        * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
        *
        * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
        *  are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
        * @param current current value
        * @param target target value
        * @param maxDelta max distance to move
        * @returns resulting angle
        */
        Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
            var num = Scalar.DeltaAngle(current, target);
            var result = 0;
            if (-maxDelta < num && num < maxDelta) {
                result = target;
            }
            else {
                target = current + num;
                result = Scalar.MoveTowards(current, target, maxDelta);
            }
            return result;
        };
        /**
         * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
         * @param start start value
         * @param end target value
         * @param amount amount to lerp between
         * @returns the lerped value
         */
        Scalar.Lerp = function (start, end, amount) {
            return start + ((end - start) * amount);
        };
        /**
        * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
        * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
        * @param start start value
        * @param end target value
        * @param amount amount to lerp between
        * @returns the lerped value
        */
        Scalar.LerpAngle = function (start, end, amount) {
            var num = Scalar.Repeat(end - start, 360.0);
            if (num > 180.0) {
                num -= 360.0;
            }
            return start + num * Scalar.Clamp(amount);
        };
        /**
        * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
        * @param a start value
        * @param b target value
        * @param value value between a and b
        * @returns the inverseLerp value
        */
        Scalar.InverseLerp = function (a, b, value) {
            var result = 0;
            if (a != b) {
                result = Scalar.Clamp((value - a) / (b - a));
            }
            else {
                result = 0.0;
            }
            return result;
        };
        /**
         * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
         * @see http://mathworld.wolfram.com/HermitePolynomial.html
         * @param value1 spline value
         * @param tangent1 spline value
         * @param value2 spline value
         * @param tangent2 spline value
         * @param amount input value
         * @returns hermite result
         */
        Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
            var squared = amount * amount;
            var cubed = amount * squared;
            var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
            var part2 = (-2.0 * cubed) + (3.0 * squared);
            var part3 = (cubed - (2.0 * squared)) + amount;
            var part4 = cubed - squared;
            return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
        };
        /**
        * Returns a random float number between and min and max values
        * @param min min value of random
        * @param max max value of random
        * @returns random value
        */
        Scalar.RandomRange = function (min, max) {
            if (min === max) {
                return min;
            }
            return ((Math.random() * (max - min)) + min);
        };
        /**
        * This function returns percentage of a number in a given range.
        *
        * RangeToPercent(40,20,60) will return 0.5 (50%)
        * RangeToPercent(34,0,100) will return 0.34 (34%)
        * @param number to convert to percentage
        * @param min min range
        * @param max max range
        * @returns the percentage
        */
        Scalar.RangeToPercent = function (number, min, max) {
            return ((number - min) / (max - min));
        };
        /**
        * This function returns number that corresponds to the percentage in a given range.
        *
        * PercentToRange(0.34,0,100) will return 34.
        * @param percent to convert to number
        * @param min min range
        * @param max max range
        * @returns the number
        */
        Scalar.PercentToRange = function (percent, min, max) {
            return ((max - min) * percent + min);
        };
        /**
         * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
         * @param angle The angle to normalize in radian.
         * @return The converted angle.
         */
        Scalar.NormalizeRadians = function (angle) {
            // More precise but slower version kept for reference.
            // angle = angle % Tools.TwoPi;
            // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
            //if (angle > Math.PI) {
            //	angle -= Tools.TwoPi;
            //}
            angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
            return angle;
        };
        /**
         * Two pi constants convenient for computation.
         */
        Scalar.TwoPi = Math.PI * 2;
        return Scalar;
    }());
    BABYLON.Scalar = Scalar;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.math.scalar.js.map



//# sourceMappingURL=babylon.mixins.js.map

// Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
// Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
// Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

//# sourceMappingURL=babylon.webgl2.js.map

var BABYLON;
(function (BABYLON) {
    var __decoratorInitialStore = {};
    var __mergedStore = {};
    var _copySource = function (creationFunction, source, instanciate) {
        var destination = creationFunction();
        // Tags
        if (BABYLON.Tags) {
            BABYLON.Tags.AddTagsTo(destination, source.tags);
        }
        var classStore = getMergedStore(destination);
        // Properties
        for (var property in classStore) {
            var propertyDescriptor = classStore[property];
            var sourceProperty = source[property];
            var propertyType = propertyDescriptor.type;
            if (sourceProperty !== undefined && sourceProperty !== null) {
                switch (propertyType) {
                    case 0: // Value
                    case 6: // Mesh reference
                    case 11: // Camera reference
                        destination[property] = sourceProperty;
                        break;
                    case 1: // Texture
                        destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
                        break;
                    case 2: // Color3
                    case 3: // FresnelParameters
                    case 4: // Vector2
                    case 5: // Vector3
                    case 7: // Color Curves
                    case 10: // Quaternion
                        destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
                        break;
                }
            }
        }
        return destination;
    };
    function getDirectStore(target) {
        var classKey = target.getClassName();
        if (!__decoratorInitialStore[classKey]) {
            __decoratorInitialStore[classKey] = {};
        }
        return __decoratorInitialStore[classKey];
    }
    /**
     * Return the list of properties flagged as serializable
     * @param target: host object
     */
    function getMergedStore(target) {
        var classKey = target.getClassName();
        if (__mergedStore[classKey]) {
            return __mergedStore[classKey];
        }
        __mergedStore[classKey] = {};
        var store = __mergedStore[classKey];
        var currentTarget = target;
        var currentKey = classKey;
        while (currentKey) {
            var initialStore = __decoratorInitialStore[currentKey];
            for (var property in initialStore) {
                store[property] = initialStore[property];
            }
            var parent_1 = void 0;
            var done = false;
            do {
                parent_1 = Object.getPrototypeOf(currentTarget);
                if (!parent_1.getClassName) {
                    done = true;
                    break;
                }
                if (parent_1.getClassName() !== currentKey) {
                    break;
                }
                currentTarget = parent_1;
            } while (parent_1);
            if (done) {
                break;
            }
            currentKey = parent_1.getClassName();
            currentTarget = parent_1;
        }
        return store;
    }
    function generateSerializableMember(type, sourceName) {
        return function (target, propertyKey) {
            var classStore = getDirectStore(target);
            if (!classStore[propertyKey]) {
                classStore[propertyKey] = { type: type, sourceName: sourceName };
            }
        };
    }
    function generateExpandMember(setCallback, targetKey) {
        if (targetKey === void 0) { targetKey = null; }
        return function (target, propertyKey) {
            var key = targetKey || ("_" + propertyKey);
            Object.defineProperty(target, propertyKey, {
                get: function () {
                    return this[key];
                },
                set: function (value) {
                    if (this[key] === value) {
                        return;
                    }
                    this[key] = value;
                    target[setCallback].apply(this);
                },
                enumerable: true,
                configurable: true
            });
        };
    }
    function expandToProperty(callback, targetKey) {
        if (targetKey === void 0) { targetKey = null; }
        return generateExpandMember(callback, targetKey);
    }
    BABYLON.expandToProperty = expandToProperty;
    function serialize(sourceName) {
        return generateSerializableMember(0, sourceName); // value member
    }
    BABYLON.serialize = serialize;
    function serializeAsTexture(sourceName) {
        return generateSerializableMember(1, sourceName); // texture member
    }
    BABYLON.serializeAsTexture = serializeAsTexture;
    function serializeAsColor3(sourceName) {
        return generateSerializableMember(2, sourceName); // color3 member
    }
    BABYLON.serializeAsColor3 = serializeAsColor3;
    function serializeAsFresnelParameters(sourceName) {
        return generateSerializableMember(3, sourceName); // fresnel parameters member
    }
    BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
    function serializeAsVector2(sourceName) {
        return generateSerializableMember(4, sourceName); // vector2 member
    }
    BABYLON.serializeAsVector2 = serializeAsVector2;
    function serializeAsVector3(sourceName) {
        return generateSerializableMember(5, sourceName); // vector3 member
    }
    BABYLON.serializeAsVector3 = serializeAsVector3;
    function serializeAsMeshReference(sourceName) {
        return generateSerializableMember(6, sourceName); // mesh reference member
    }
    BABYLON.serializeAsMeshReference = serializeAsMeshReference;
    function serializeAsColorCurves(sourceName) {
        return generateSerializableMember(7, sourceName); // color curves
    }
    BABYLON.serializeAsColorCurves = serializeAsColorCurves;
    function serializeAsColor4(sourceName) {
        return generateSerializableMember(8, sourceName); // color 4
    }
    BABYLON.serializeAsColor4 = serializeAsColor4;
    function serializeAsImageProcessingConfiguration(sourceName) {
        return generateSerializableMember(9, sourceName); // image processing
    }
    BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
    function serializeAsQuaternion(sourceName) {
        return generateSerializableMember(10, sourceName); // quaternion member
    }
    BABYLON.serializeAsQuaternion = serializeAsQuaternion;
    /**
     * Decorator used to define property that can be serialized as reference to a camera
     * @param sourceName defines the name of the property to decorate
     */
    function serializeAsCameraReference(sourceName) {
        return generateSerializableMember(11, sourceName); // camera reference member
    }
    BABYLON.serializeAsCameraReference = serializeAsCameraReference;
    /**
     * Class used to help serialization objects
     */
    var SerializationHelper = /** @class */ (function () {
        function SerializationHelper() {
        }
        /**
         * Static function used to serialized a specific entity
         * @param entity defines the entity to serialize
         * @param serializationObject defines the optional target obecjt where serialization data will be stored
         * @returns a JSON compatible object representing the serialization of the entity
         */
        SerializationHelper.Serialize = function (entity, serializationObject) {
            if (!serializationObject) {
                serializationObject = {};
            }
            // Tags
            if (BABYLON.Tags) {
                serializationObject.tags = BABYLON.Tags.GetTags(entity);
            }
            var serializedProperties = getMergedStore(entity);
            // Properties
            for (var property in serializedProperties) {
                var propertyDescriptor = serializedProperties[property];
                var targetPropertyName = propertyDescriptor.sourceName || property;
                var propertyType = propertyDescriptor.type;
                var sourceProperty = entity[property];
                if (sourceProperty !== undefined && sourceProperty !== null) {
                    switch (propertyType) {
                        case 0: // Value
                            serializationObject[targetPropertyName] = sourceProperty;
                            break;
                        case 1: // Texture
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                        case 2: // Color3
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 3: // FresnelParameters
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                        case 4: // Vector2
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 5: // Vector3
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 6: // Mesh reference
                            serializationObject[targetPropertyName] = sourceProperty.id;
                            break;
                        case 7: // Color Curves
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                        case 8: // Color 4
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 9: // Image Processing
                            serializationObject[targetPropertyName] = sourceProperty.serialize();
                            break;
                        case 10: // Quaternion
                            serializationObject[targetPropertyName] = sourceProperty.asArray();
                            break;
                        case 11: // Camera reference
                            serializationObject[targetPropertyName] = sourceProperty.id;
                            break;
                    }
                }
            }
            return serializationObject;
        };
        /**
         * Creates a new entity from a serialization data object
         * @param creationFunction defines a function used to instanciated the new entity
         * @param source defines the source serialization data
         * @param scene defines the hosting scene
         * @param rootUrl defines the root url for resources
         * @returns a new entity
         */
        SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
            if (rootUrl === void 0) { rootUrl = null; }
            var destination = creationFunction();
            if (!rootUrl) {
                rootUrl = "";
            }
            // Tags
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(destination, source.tags);
            }
            var classStore = getMergedStore(destination);
            // Properties
            for (var property in classStore) {
                var propertyDescriptor = classStore[property];
                var sourceProperty = source[propertyDescriptor.sourceName || property];
                var propertyType = propertyDescriptor.type;
                if (sourceProperty !== undefined && sourceProperty !== null) {
                    var dest = destination;
                    switch (propertyType) {
                        case 0: // Value
                            dest[property] = sourceProperty;
                            break;
                        case 1: // Texture
                            if (scene) {
                                dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
                            }
                            break;
                        case 2: // Color3
                            dest[property] = BABYLON.Color3.FromArray(sourceProperty);
                            break;
                        case 3: // FresnelParameters
                            dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
                            break;
                        case 4: // Vector2
                            dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
                            break;
                        case 5: // Vector3
                            dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
                            break;
                        case 6: // Mesh reference
                            if (scene) {
                                dest[property] = scene.getLastMeshByID(sourceProperty);
                            }
                            break;
                        case 7: // Color Curves
                            dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
                            break;
                        case 8: // Color 4
                            dest[property] = BABYLON.Color4.FromArray(sourceProperty);
                            break;
                        case 9: // Image Processing
                            dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
                            break;
                        case 10: // Quaternion
                            dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
                            break;
                        case 11: // Camera reference
                            if (scene) {
                                dest[property] = scene.getCameraByID(sourceProperty);
                            }
                            break;
                    }
                }
            }
            return destination;
        };
        /**
         * Clones an object
         * @param creationFunction defines the function used to instanciate the new object
         * @param source defines the source object
         * @returns the cloned object
         */
        SerializationHelper.Clone = function (creationFunction, source) {
            return _copySource(creationFunction, source, false);
        };
        /**
         * Instanciates a new object based on a source one (some data will be shared between both object)
         * @param creationFunction defines the function used to instanciate the new object
         * @param source defines the source object
         * @returns the new object
         */
        SerializationHelper.Instanciate = function (creationFunction, source) {
            return _copySource(creationFunction, source, true);
        };
        return SerializationHelper;
    }());
    BABYLON.SerializationHelper = SerializationHelper;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.decorators.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Wrapper class for promise with external resolve and reject.
     */
    var Deferred = /** @class */ (function () {
        /**
         * Constructor for this deferred object.
         */
        function Deferred() {
            var _this = this;
            this.promise = new Promise(function (resolve, reject) {
                _this._resolve = resolve;
                _this._reject = reject;
            });
        }
        Object.defineProperty(Deferred.prototype, "resolve", {
            /**
             * The resolve method of the promise associated with this deferred object.
             */
            get: function () {
                return this._resolve;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Deferred.prototype, "reject", {
            /**
             * The reject method of the promise associated with this deferred object.
             */
            get: function () {
                return this._reject;
            },
            enumerable: true,
            configurable: true
        });
        return Deferred;
    }());
    BABYLON.Deferred = Deferred;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.deferred.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A class serves as a medium between the observable and its observers
     */
    var EventState = /** @class */ (function () {
        /**
         * Create a new EventState
         * @param mask defines the mask associated with this state
         * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
         * @param target defines the original target of the state
         * @param currentTarget defines the current target of the state
         */
        function EventState(mask, skipNextObservers, target, currentTarget) {
            if (skipNextObservers === void 0) { skipNextObservers = false; }
            this.initalize(mask, skipNextObservers, target, currentTarget);
        }
        /**
         * Initialize the current event state
         * @param mask defines the mask associated with this state
         * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
         * @param target defines the original target of the state
         * @param currentTarget defines the current target of the state
         * @returns the current event state
         */
        EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
            if (skipNextObservers === void 0) { skipNextObservers = false; }
            this.mask = mask;
            this.skipNextObservers = skipNextObservers;
            this.target = target;
            this.currentTarget = currentTarget;
            return this;
        };
        return EventState;
    }());
    BABYLON.EventState = EventState;
    /**
     * Represent an Observer registered to a given Observable object.
     */
    var Observer = /** @class */ (function () {
        /**
         * Creates a new observer
         * @param callback defines the callback to call when the observer is notified
         * @param mask defines the mask of the observer (used to filter notifications)
         * @param scope defines the current scope used to restore the JS context
         */
        function Observer(
        /**
         * Defines the callback to call when the observer is notified
         */
        callback, 
        /**
         * Defines the mask of the observer (used to filter notifications)
         */
        mask, 
        /**
         * Defines the current scope used to restore the JS context
         */
        scope) {
            if (scope === void 0) { scope = null; }
            this.callback = callback;
            this.mask = mask;
            this.scope = scope;
            /** @hidden */
            this._willBeUnregistered = false;
            /**
             * Gets or sets a property defining that the observer as to be unregistered after the next notification
             */
            this.unregisterOnNextCall = false;
        }
        return Observer;
    }());
    BABYLON.Observer = Observer;
    /**
     * Represent a list of observers registered to multiple Observables object.
     */
    var MultiObserver = /** @class */ (function () {
        function MultiObserver() {
        }
        /**
         * Release associated resources
         */
        MultiObserver.prototype.dispose = function () {
            if (this._observers && this._observables) {
                for (var index = 0; index < this._observers.length; index++) {
                    this._observables[index].remove(this._observers[index]);
                }
            }
            this._observers = null;
            this._observables = null;
        };
        /**
         * Raise a callback when one of the observable will notify
         * @param observables defines a list of observables to watch
         * @param callback defines the callback to call on notification
         * @param mask defines the mask used to filter notifications
         * @param scope defines the current scope used to restore the JS context
         * @returns the new MultiObserver
         */
        MultiObserver.Watch = function (observables, callback, mask, scope) {
            if (mask === void 0) { mask = -1; }
            if (scope === void 0) { scope = null; }
            var result = new MultiObserver();
            result._observers = new Array();
            result._observables = observables;
            for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
                var observable = observables_1[_i];
                var observer = observable.add(callback, mask, false, scope);
                if (observer) {
                    result._observers.push(observer);
                }
            }
            return result;
        };
        return MultiObserver;
    }());
    BABYLON.MultiObserver = MultiObserver;
    /**
     * The Observable class is a simple implementation of the Observable pattern.
     *
     * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
     * This enable a more fine grained execution without having to rely on multiple different Observable objects.
     * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
     * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
     */
    var Observable = /** @class */ (function () {
        /**
         * Creates a new observable
         * @param onObserverAdded defines a callback to call when a new observer is added
         */
        function Observable(onObserverAdded) {
            this._observers = new Array();
            this._eventState = new EventState(0);
            if (onObserverAdded) {
                this._onObserverAdded = onObserverAdded;
            }
        }
        /**
         * Create a new Observer with the specified callback
         * @param callback the callback that will be executed for that Observer
         * @param mask the mask used to filter observers
         * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
         * @param scope optional scope for the callback to be called from
         * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
         * @returns the new observer created for the callback
         */
        Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
            if (mask === void 0) { mask = -1; }
            if (insertFirst === void 0) { insertFirst = false; }
            if (scope === void 0) { scope = null; }
            if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
            if (!callback) {
                return null;
            }
            var observer = new Observer(callback, mask, scope);
            observer.unregisterOnNextCall = unregisterOnFirstCall;
            if (insertFirst) {
                this._observers.unshift(observer);
            }
            else {
                this._observers.push(observer);
            }
            if (this._onObserverAdded) {
                this._onObserverAdded(observer);
            }
            return observer;
        };
        /**
         * Create a new Observer with the specified callback and unregisters after the next notification
         * @param callback the callback that will be executed for that Observer
         * @returns the new observer created for the callback
         */
        Observable.prototype.addOnce = function (callback) {
            return this.add(callback, undefined, undefined, undefined, true);
        };
        /**
         * Remove an Observer from the Observable object
         * @param observer the instance of the Observer to remove
         * @returns false if it doesn't belong to this Observable
         */
        Observable.prototype.remove = function (observer) {
            if (!observer) {
                return false;
            }
            var index = this._observers.indexOf(observer);
            if (index !== -1) {
                this._deferUnregister(observer);
                return true;
            }
            return false;
        };
        /**
         * Remove a callback from the Observable object
         * @param callback the callback to remove
         * @param scope optional scope. If used only the callbacks with this scope will be removed
         * @returns false if it doesn't belong to this Observable
        */
        Observable.prototype.removeCallback = function (callback, scope) {
            for (var index = 0; index < this._observers.length; index++) {
                if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
                    this._deferUnregister(this._observers[index]);
                    return true;
                }
            }
            return false;
        };
        Observable.prototype._deferUnregister = function (observer) {
            var _this = this;
            observer.unregisterOnNextCall = false;
            observer._willBeUnregistered = true;
            BABYLON.Tools.SetImmediate(function () {
                _this._remove(observer);
            });
        };
        // This should only be called when not iterating over _observers to avoid callback skipping.
        // Removes an observer from the _observer Array.
        Observable.prototype._remove = function (observer) {
            if (!observer) {
                return false;
            }
            var index = this._observers.indexOf(observer);
            if (index !== -1) {
                this._observers.splice(index, 1);
                return true;
            }
            return false;
        };
        /**
         * Notify all Observers by calling their respective callback with the given data
         * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
         * @param eventData defines the data to send to all observers
         * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
         * @param target defines the original target of the state
         * @param currentTarget defines the current target of the state
         * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
         */
        Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
            if (mask === void 0) { mask = -1; }
            if (!this._observers.length) {
                return true;
            }
            var state = this._eventState;
            state.mask = mask;
            state.target = target;
            state.currentTarget = currentTarget;
            state.skipNextObservers = false;
            state.lastReturnValue = eventData;
            for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
                var obs = _a[_i];
                if (obs._willBeUnregistered) {
                    continue;
                }
                if (obs.mask & mask) {
                    if (obs.scope) {
                        state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
                    }
                    else {
                        state.lastReturnValue = obs.callback(eventData, state);
                    }
                    if (obs.unregisterOnNextCall) {
                        this._deferUnregister(obs);
                    }
                }
                if (state.skipNextObservers) {
                    return false;
                }
            }
            return true;
        };
        /**
         * Calling this will execute each callback, expecting it to be a promise or return a value.
         * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
         * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
         * and it is crucial that all callbacks will be executed.
         * The order of the callbacks is kept, callbacks are not executed parallel.
         *
         * @param eventData The data to be sent to each callback
         * @param mask is used to filter observers defaults to -1
         * @param target defines the callback target (see EventState)
         * @param currentTarget defines he current object in the bubbling phase
         * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
         */
        Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
            var _this = this;
            if (mask === void 0) { mask = -1; }
            // create an empty promise
            var p = Promise.resolve(eventData);
            // no observers? return this promise.
            if (!this._observers.length) {
                return p;
            }
            var state = this._eventState;
            state.mask = mask;
            state.target = target;
            state.currentTarget = currentTarget;
            state.skipNextObservers = false;
            // execute one callback after another (not using Promise.all, the order is important)
            this._observers.forEach(function (obs) {
                if (state.skipNextObservers) {
                    return;
                }
                if (obs._willBeUnregistered) {
                    return;
                }
                if (obs.mask & mask) {
                    if (obs.scope) {
                        p = p.then(function (lastReturnedValue) {
                            state.lastReturnValue = lastReturnedValue;
                            return obs.callback.apply(obs.scope, [eventData, state]);
                        });
                    }
                    else {
                        p = p.then(function (lastReturnedValue) {
                            state.lastReturnValue = lastReturnedValue;
                            return obs.callback(eventData, state);
                        });
                    }
                    if (obs.unregisterOnNextCall) {
                        _this._deferUnregister(obs);
                    }
                }
            });
            // return the eventData
            return p.then(function () { return eventData; });
        };
        /**
         * Notify a specific observer
         * @param observer defines the observer to notify
         * @param eventData defines the data to be sent to each callback
         * @param mask is used to filter observers defaults to -1
         */
        Observable.prototype.notifyObserver = function (observer, eventData, mask) {
            if (mask === void 0) { mask = -1; }
            var state = this._eventState;
            state.mask = mask;
            state.skipNextObservers = false;
            observer.callback(eventData, state);
        };
        /**
         * Gets a boolean indicating if the observable has at least one observer
         * @returns true is the Observable has at least one Observer registered
         */
        Observable.prototype.hasObservers = function () {
            return this._observers.length > 0;
        };
        /**
        * Clear the list of observers
        */
        Observable.prototype.clear = function () {
            this._observers = new Array();
            this._onObserverAdded = null;
        };
        /**
         * Clone the current observable
         * @returns a new observable
         */
        Observable.prototype.clone = function () {
            var result = new Observable();
            result._observers = this._observers.slice(0);
            return result;
        };
        /**
         * Does this observable handles observer registered with a given mask
         * @param mask defines the mask to be tested
         * @return whether or not one observer registered with the given mask is handeled
        **/
        Observable.prototype.hasSpecificMask = function (mask) {
            if (mask === void 0) { mask = -1; }
            for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
                var obs = _a[_i];
                if (obs.mask & mask || obs.mask === mask) {
                    return true;
                }
            }
            return false;
        };
        return Observable;
    }());
    BABYLON.Observable = Observable;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.observable.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
     */
    var SmartArray = /** @class */ (function () {
        /**
         * Instantiates a Smart Array.
         * @param capacity defines the default capacity of the array.
         */
        function SmartArray(capacity) {
            /**
             * The active length of the array.
             */
            this.length = 0;
            this.data = new Array(capacity);
            this._id = SmartArray._GlobalId++;
        }
        /**
         * Pushes a value at the end of the active data.
         * @param value defines the object to push in the array.
         */
        SmartArray.prototype.push = function (value) {
            this.data[this.length++] = value;
            if (this.length > this.data.length) {
                this.data.length *= 2;
            }
        };
        /**
         * Iterates over the active data and apply the lambda to them.
         * @param func defines the action to apply on each value.
         */
        SmartArray.prototype.forEach = function (func) {
            for (var index = 0; index < this.length; index++) {
                func(this.data[index]);
            }
        };
        /**
         * Sorts the full sets of data.
         * @param compareFn defines the comparison function to apply.
         */
        SmartArray.prototype.sort = function (compareFn) {
            this.data.sort(compareFn);
        };
        /**
         * Resets the active data to an empty array.
         */
        SmartArray.prototype.reset = function () {
            this.length = 0;
        };
        /**
         * Releases all the data from the array as well as the array.
         */
        SmartArray.prototype.dispose = function () {
            this.reset();
            if (this.data) {
                this.data.length = 0;
                this.data = [];
            }
        };
        /**
         * Concats the active data with a given array.
         * @param array defines the data to concatenate with.
         */
        SmartArray.prototype.concat = function (array) {
            if (array.length === 0) {
                return;
            }
            if (this.length + array.length > this.data.length) {
                this.data.length = (this.length + array.length) * 2;
            }
            for (var index = 0; index < array.length; index++) {
                this.data[this.length++] = (array.data || array)[index];
            }
        };
        /**
         * Returns the position of a value in the active data.
         * @param value defines the value to find the index for
         * @returns the index if found in the active data otherwise -1
         */
        SmartArray.prototype.indexOf = function (value) {
            var position = this.data.indexOf(value);
            if (position >= this.length) {
                return -1;
            }
            return position;
        };
        /**
         * Returns whether an element is part of the active data.
         * @param value defines the value to look for
         * @returns true if found in the active data otherwise false
         */
        SmartArray.prototype.contains = function (value) {
            return this.indexOf(value) !== -1;
        };
        // Statics
        SmartArray._GlobalId = 0;
        return SmartArray;
    }());
    BABYLON.SmartArray = SmartArray;
    /**
     * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
     * The data in this array can only be present once
     */
    var SmartArrayNoDuplicate = /** @class */ (function (_super) {
        __extends(SmartArrayNoDuplicate, _super);
        function SmartArrayNoDuplicate() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._duplicateId = 0;
            return _this;
        }
        /**
         * Pushes a value at the end of the active data.
         * THIS DOES NOT PREVENT DUPPLICATE DATA
         * @param value defines the object to push in the array.
         */
        SmartArrayNoDuplicate.prototype.push = function (value) {
            _super.prototype.push.call(this, value);
            if (!value.__smartArrayFlags) {
                value.__smartArrayFlags = {};
            }
            value.__smartArrayFlags[this._id] = this._duplicateId;
        };
        /**
         * Pushes a value at the end of the active data.
         * If the data is already present, it won t be added again
         * @param value defines the object to push in the array.
         * @returns true if added false if it was already present
         */
        SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
            if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
                return false;
            }
            this.push(value);
            return true;
        };
        /**
         * Resets the active data to an empty array.
         */
        SmartArrayNoDuplicate.prototype.reset = function () {
            _super.prototype.reset.call(this);
            this._duplicateId++;
        };
        /**
         * Concats the active data with a given array.
         * This ensures no dupplicate will be present in the result.
         * @param array defines the data to concatenate with.
         */
        SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
            if (array.length === 0) {
                return;
            }
            if (this.length + array.length > this.data.length) {
                this.data.length = (this.length + array.length) * 2;
            }
            for (var index = 0; index < array.length; index++) {
                var item = (array.data || array)[index];
                this.pushNoDuplicate(item);
            }
        };
        return SmartArrayNoDuplicate;
    }(SmartArray));
    BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.smartArray.js.map


var BABYLON;
(function (BABYLON) {
    /** Class used to store color4 gradient */
    var ColorGradient = /** @class */ (function () {
        function ColorGradient() {
        }
        /**
         * Will get a color picked randomly between color1 and color2.
         * If color2 is undefined then color1 will be used
         * @param result defines the target Color4 to store the result in
         */
        ColorGradient.prototype.getColorToRef = function (result) {
            if (!this.color2) {
                result.copyFrom(this.color1);
                return;
            }
            BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
        };
        return ColorGradient;
    }());
    BABYLON.ColorGradient = ColorGradient;
    /** Class used to store color 3 gradient */
    var Color3Gradient = /** @class */ (function () {
        function Color3Gradient() {
        }
        return Color3Gradient;
    }());
    BABYLON.Color3Gradient = Color3Gradient;
    /** Class used to store factor gradient */
    var FactorGradient = /** @class */ (function () {
        function FactorGradient() {
        }
        /**
         * Will get a number picked randomly between factor1 and factor2.
         * If factor2 is undefined then factor1 will be used
         * @returns the picked number
         */
        FactorGradient.prototype.getFactor = function () {
            if (this.factor2 === undefined) {
                return this.factor1;
            }
            return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
        };
        return FactorGradient;
    }());
    BABYLON.FactorGradient = FactorGradient;
    /**
     * @ignore
     * Application error to support additional information when loading a file
     */
    var LoadFileError = /** @class */ (function (_super) {
        __extends(LoadFileError, _super);
        /**
         * Creates a new LoadFileError
         * @param message defines the message of the error
         * @param request defines the optional XHR request
         */
        function LoadFileError(message, 
        /** defines the optional XHR request */
        request) {
            var _this = _super.call(this, message) || this;
            _this.request = request;
            _this.name = "LoadFileError";
            LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
            return _this;
        }
        // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
        // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
        // Polyfill for Object.setPrototypeOf if necessary.
        LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
        return LoadFileError;
    }(Error));
    BABYLON.LoadFileError = LoadFileError;
    /**
     * Class used to define a retry strategy when error happens while loading assets
     */
    var RetryStrategy = /** @class */ (function () {
        function RetryStrategy() {
        }
        /**
         * Function used to defines an exponential back off strategy
         * @param maxRetries defines the maximum number of retries (3 by default)
         * @param baseInterval defines the interval between retries
         * @returns the strategy function to use
         */
        RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
            if (maxRetries === void 0) { maxRetries = 3; }
            if (baseInterval === void 0) { baseInterval = 500; }
            return function (url, request, retryIndex) {
                if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
                    return -1;
                }
                return Math.pow(2, retryIndex) * baseInterval;
            };
        };
        return RetryStrategy;
    }());
    BABYLON.RetryStrategy = RetryStrategy;
    // Screenshots
    var screenshotCanvas;
    var cloneValue = function (source, destinationObject) {
        if (!source) {
            return null;
        }
        if (source instanceof BABYLON.Mesh) {
            return null;
        }
        if (source instanceof BABYLON.SubMesh) {
            return source.clone(destinationObject);
        }
        else if (source.clone) {
            return source.clone();
        }
        return null;
    };
    /**
     * Class containing a set of static utilities functions
     */
    var Tools = /** @class */ (function () {
        function Tools() {
        }
        /**
         * Read the content of a byte array at a specified coordinates (taking in account wrapping)
         * @param u defines the coordinate on X axis
         * @param v defines the coordinate on Y axis
         * @param width defines the width of the source data
         * @param height defines the height of the source data
         * @param pixels defines the source byte array
         * @param color defines the output color
         */
        Tools.FetchToRef = function (u, v, width, height, pixels, color) {
            var wrappedU = ((Math.abs(u) * width) % width) | 0;
            var wrappedV = ((Math.abs(v) * height) % height) | 0;
            var position = (wrappedU + wrappedV * width) * 4;
            color.r = pixels[position] / 255;
            color.g = pixels[position + 1] / 255;
            color.b = pixels[position + 2] / 255;
            color.a = pixels[position + 3] / 255;
        };
        /**
         * Interpolates between a and b via alpha
         * @param a The lower value (returned when alpha = 0)
         * @param b The upper value (returned when alpha = 1)
         * @param alpha The interpolation-factor
         * @return The mixed value
         */
        Tools.Mix = function (a, b, alpha) {
            return a * (1 - alpha) + b * alpha;
        };
        /**
         * Tries to instantiate a new object from a given class name
         * @param className defines the class name to instantiate
         * @returns the new object or null if the system was not able to do the instantiation
         */
        Tools.Instantiate = function (className) {
            if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
                return Tools.RegisteredExternalClasses[className];
            }
            var arr = className.split(".");
            var fn = (window || this);
            for (var i = 0, len = arr.length; i < len; i++) {
                fn = fn[arr[i]];
            }
            if (typeof fn !== "function") {
                return null;
            }
            return fn;
        };
        /**
         * Provides a slice function that will work even on IE
         * @param data defines the array to slice
         * @param start defines the start of the data (optional)
         * @param end defines the end of the data (optional)
         * @returns the new sliced array
         */
        Tools.Slice = function (data, start, end) {
            if (data.slice) {
                return data.slice(start, end);
            }
            return Array.prototype.slice.call(data, start, end);
        };
        /**
         * Polyfill for setImmediate
         * @param action defines the action to execute after the current execution block
         */
        Tools.SetImmediate = function (action) {
            if (Tools.IsWindowObjectExist() && window.setImmediate) {
                window.setImmediate(action);
            }
            else {
                setTimeout(action, 1);
            }
        };
        /**
         * Function indicating if a number is an exponent of 2
         * @param value defines the value to test
         * @returns true if the value is an exponent of 2
         */
        Tools.IsExponentOfTwo = function (value) {
            var count = 1;
            do {
                count *= 2;
            } while (count < value);
            return count === value;
        };
        /**
         * Returns the nearest 32-bit single precision float representation of a Number
         * @param value A Number.  If the parameter is of a different type, it will get converted
         * to a number or to NaN if it cannot be converted
         * @returns number
         */
        Tools.FloatRound = function (value) {
            if (Math.fround) {
                return Math.fround(value);
            }
            return (Tools._tmpFloatArray[0] = value);
        };
        /**
         * Find the next highest power of two.
         * @param x Number to start search from.
         * @return Next highest power of two.
         */
        Tools.CeilingPOT = function (x) {
            x--;
            x |= x >> 1;
            x |= x >> 2;
            x |= x >> 4;
            x |= x >> 8;
            x |= x >> 16;
            x++;
            return x;
        };
        /**
         * Find the next lowest power of two.
         * @param x Number to start search from.
         * @return Next lowest power of two.
         */
        Tools.FloorPOT = function (x) {
            x = x | (x >> 1);
            x = x | (x >> 2);
            x = x | (x >> 4);
            x = x | (x >> 8);
            x = x | (x >> 16);
            return x - (x >> 1);
        };
        /**
         * Find the nearest power of two.
         * @param x Number to start search from.
         * @return Next nearest power of two.
         */
        Tools.NearestPOT = function (x) {
            var c = Tools.CeilingPOT(x);
            var f = Tools.FloorPOT(x);
            return (c - x) > (x - f) ? f : c;
        };
        /**
         * Get the closest exponent of two
         * @param value defines the value to approximate
         * @param max defines the maximum value to return
         * @param mode defines how to define the closest value
         * @returns closest exponent of two of the given value
         */
        Tools.GetExponentOfTwo = function (value, max, mode) {
            if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
            var pot;
            switch (mode) {
                case BABYLON.Engine.SCALEMODE_FLOOR:
                    pot = Tools.FloorPOT(value);
                    break;
                case BABYLON.Engine.SCALEMODE_NEAREST:
                    pot = Tools.NearestPOT(value);
                    break;
                case BABYLON.Engine.SCALEMODE_CEILING:
                default:
                    pot = Tools.CeilingPOT(value);
                    break;
            }
            return Math.min(pot, max);
        };
        /**
         * Extracts the filename from a path
         * @param path defines the path to use
         * @returns the filename
         */
        Tools.GetFilename = function (path) {
            var index = path.lastIndexOf("/");
            if (index < 0) {
                return path;
            }
            return path.substring(index + 1);
        };
        /**
         * Extracts the "folder" part of a path (everything before the filename).
         * @param uri The URI to extract the info from
         * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
         * @returns The "folder" part of the path
         */
        Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
            if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
            var index = uri.lastIndexOf("/");
            if (index < 0) {
                if (returnUnchangedIfNoSlash) {
                    return uri;
                }
                return "";
            }
            return uri.substring(0, index + 1);
        };
        /**
         * Extracts text content from a DOM element hierarchy
         * @param element defines the root element
         * @returns a string
         */
        Tools.GetDOMTextContent = function (element) {
            var result = "";
            var child = element.firstChild;
            while (child) {
                if (child.nodeType === 3) {
                    result += child.textContent;
                }
                child = child.nextSibling;
            }
            return result;
        };
        /**
         * Convert an angle in radians to degrees
         * @param angle defines the angle to convert
         * @returns the angle in degrees
         */
        Tools.ToDegrees = function (angle) {
            return angle * 180 / Math.PI;
        };
        /**
         * Convert an angle in degrees to radians
         * @param angle defines the angle to convert
         * @returns the angle in radians
         */
        Tools.ToRadians = function (angle) {
            return angle * Math.PI / 180;
        };
        /**
         * Encode a buffer to a base64 string
         * @param buffer defines the buffer to encode
         * @returns the encoded string
         */
        Tools.EncodeArrayBufferTobase64 = function (buffer) {
            var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            var bytes = new Uint8Array(buffer);
            while (i < bytes.length) {
                chr1 = bytes[i++];
                chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
                chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                }
                else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
                    keyStr.charAt(enc3) + keyStr.charAt(enc4);
            }
            return "data:image/png;base64," + output;
        };
        /**
         * Extracts minimum and maximum values from a list of indexed positions
         * @param positions defines the positions to use
         * @param indices defines the indices to the positions
         * @param indexStart defines the start index
         * @param indexCount defines the end index
         * @param bias defines bias value to add to the result
         * @return minimum and maximum values
         */
        Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
            if (bias === void 0) { bias = null; }
            var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            for (var index = indexStart; index < indexStart + indexCount; index++) {
                var offset = indices[index] * 3;
                var x = positions[offset];
                var y = positions[offset + 1];
                var z = positions[offset + 2];
                minimum.minimizeInPlaceFromFloats(x, y, z);
                maximum.maximizeInPlaceFromFloats(x, y, z);
            }
            if (bias) {
                minimum.x -= minimum.x * bias.x + bias.y;
                minimum.y -= minimum.y * bias.x + bias.y;
                minimum.z -= minimum.z * bias.x + bias.y;
                maximum.x += maximum.x * bias.x + bias.y;
                maximum.y += maximum.y * bias.x + bias.y;
                maximum.z += maximum.z * bias.x + bias.y;
            }
            return {
                minimum: minimum,
                maximum: maximum
            };
        };
        /**
         * Extracts minimum and maximum values from a list of positions
         * @param positions defines the positions to use
         * @param start defines the start index in the positions array
         * @param count defines the number of positions to handle
         * @param bias defines bias value to add to the result
         * @param stride defines the stride size to use (distance between two positions in the positions array)
         * @return minimum and maximum values
         */
        Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
            if (bias === void 0) { bias = null; }
            var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            if (!stride) {
                stride = 3;
            }
            for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
                var x = positions[offset];
                var y = positions[offset + 1];
                var z = positions[offset + 2];
                minimum.minimizeInPlaceFromFloats(x, y, z);
                maximum.maximizeInPlaceFromFloats(x, y, z);
            }
            if (bias) {
                minimum.x -= minimum.x * bias.x + bias.y;
                minimum.y -= minimum.y * bias.x + bias.y;
                minimum.z -= minimum.z * bias.x + bias.y;
                maximum.x += maximum.x * bias.x + bias.y;
                maximum.y += maximum.y * bias.x + bias.y;
                maximum.z += maximum.z * bias.x + bias.y;
            }
            return {
                minimum: minimum,
                maximum: maximum
            };
        };
        /**
         * Returns an array if obj is not an array
         * @param obj defines the object to evaluate as an array
         * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
         * @returns either obj directly if obj is an array or a new array containing obj
         */
        Tools.MakeArray = function (obj, allowsNullUndefined) {
            if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
                return null;
            }
            return Array.isArray(obj) ? obj : [obj];
        };
        /**
         * Gets the pointer prefix to use
         * @returns "pointer" if touch is enabled. Else returns "mouse"
         */
        Tools.GetPointerPrefix = function () {
            var eventPrefix = "pointer";
            // Check if pointer events are supported
            if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
                eventPrefix = "mouse";
            }
            return eventPrefix;
        };
        /**
         * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
         * @param func - the function to be called
         * @param requester - the object that will request the next frame. Falls back to window.
         * @returns frame number
         */
        Tools.QueueNewFrame = function (func, requester) {
            if (!Tools.IsWindowObjectExist()) {
                return setTimeout(func, 16);
            }
            if (!requester) {
                requester = window;
            }
            if (requester.requestAnimationFrame) {
                return requester.requestAnimationFrame(func);
            }
            else if (requester.msRequestAnimationFrame) {
                return requester.msRequestAnimationFrame(func);
            }
            else if (requester.webkitRequestAnimationFrame) {
                return requester.webkitRequestAnimationFrame(func);
            }
            else if (requester.mozRequestAnimationFrame) {
                return requester.mozRequestAnimationFrame(func);
            }
            else if (requester.oRequestAnimationFrame) {
                return requester.oRequestAnimationFrame(func);
            }
            else {
                return window.setTimeout(func, 16);
            }
        };
        /**
         * Ask the browser to promote the current element to fullscreen rendering mode
         * @param element defines the DOM element to promote
         */
        Tools.RequestFullscreen = function (element) {
            var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
            if (!requestFunction) {
                return;
            }
            requestFunction.call(element);
        };
        /**
         * Asks the browser to exit fullscreen mode
         */
        Tools.ExitFullscreen = function () {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
            else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            }
            else if (document.webkitCancelFullScreen) {
                document.webkitCancelFullScreen();
            }
            else if (document.msCancelFullScreen) {
                document.msCancelFullScreen();
            }
        };
        /**
         * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
         * @param url define the url we are trying
         * @param element define the dom element where to configure the cors policy
         */
        Tools.SetCorsBehavior = function (url, element) {
            if (url && url.indexOf("data:") === 0) {
                return;
            }
            if (Tools.CorsBehavior) {
                if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
                    element.crossOrigin = Tools.CorsBehavior;
                }
                else {
                    var result = Tools.CorsBehavior(url);
                    if (result) {
                        element.crossOrigin = result;
                    }
                }
            }
        };
        // External files
        /**
         * Removes unwanted characters from an url
         * @param url defines the url to clean
         * @returns the cleaned url
         */
        Tools.CleanUrl = function (url) {
            url = url.replace(/#/mg, "%23");
            return url;
        };
        /**
         * Loads an image as an HTMLImageElement.
         * @param input url string, ArrayBuffer, or Blob to load
         * @param onLoad callback called when the image successfully loads
         * @param onError callback called when the image fails to load
         * @param database database for caching
         * @returns the HTMLImageElement of the loaded image
         */
        Tools.LoadImage = function (input, onLoad, onError, database) {
            var url;
            var usingObjectURL = false;
            if (input instanceof ArrayBuffer) {
                url = URL.createObjectURL(new Blob([input]));
                usingObjectURL = true;
            }
            else if (input instanceof Blob) {
                url = URL.createObjectURL(input);
                usingObjectURL = true;
            }
            else {
                url = Tools.CleanUrl(input);
                url = Tools.PreprocessUrl(input);
            }
            var img = new Image();
            Tools.SetCorsBehavior(url, img);
            var loadHandler = function () {
                if (usingObjectURL && img.src) {
                    URL.revokeObjectURL(img.src);
                }
                img.removeEventListener("load", loadHandler);
                img.removeEventListener("error", errorHandler);
                onLoad(img);
            };
            var errorHandler = function (err) {
                if (usingObjectURL && img.src) {
                    URL.revokeObjectURL(img.src);
                }
                img.removeEventListener("load", loadHandler);
                img.removeEventListener("error", errorHandler);
                Tools.Error("Error while trying to load image: " + input);
                if (onError) {
                    onError("Error while trying to load image: " + input, err);
                }
            };
            img.addEventListener("load", loadHandler);
            img.addEventListener("error", errorHandler);
            var noIndexedDB = function () {
                img.src = url;
            };
            var loadFromIndexedDB = function () {
                if (database) {
                    database.loadImageFromDB(url, img);
                }
            };
            //ANY database to do!
            if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
                database.openAsync(loadFromIndexedDB, noIndexedDB);
            }
            else {
                if (url.indexOf("file:") !== -1) {
                    var textureName = decodeURIComponent(url.substring(5).toLowerCase());
                    if (BABYLON.FilesInput.FilesToLoad[textureName]) {
                        try {
                            var blobURL;
                            try {
                                blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
                            }
                            catch (ex) {
                                // Chrome doesn't support oneTimeOnly parameter
                                blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
                            }
                            img.src = blobURL;
                            usingObjectURL = true;
                        }
                        catch (e) {
                            img.src = "";
                        }
                        return img;
                    }
                }
                noIndexedDB();
            }
            return img;
        };
        /**
         * Loads a file
         * @param url url string, ArrayBuffer, or Blob to load
         * @param onSuccess callback called when the file successfully loads
         * @param onProgress callback called while file is loading (if the server supports this mode)
         * @param database  database for caching
         * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
         * @param onError callback called when the file fails to load
         * @returns a file request object
         */
        Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
            url = Tools.CleanUrl(url);
            url = Tools.PreprocessUrl(url);
            // If file and file input are set
            if (url.indexOf("file:") !== -1) {
                var fileName = decodeURIComponent(url.substring(5).toLowerCase());
                if (BABYLON.FilesInput.FilesToLoad[fileName]) {
                    return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
                }
            }
            var loadUrl = Tools.BaseUrl + url;
            var aborted = false;
            var fileRequest = {
                onCompleteObservable: new BABYLON.Observable(),
                abort: function () { return aborted = true; },
            };
            var requestFile = function () {
                var request = new XMLHttpRequest();
                var retryHandle = null;
                fileRequest.abort = function () {
                    aborted = true;
                    if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
                        request.abort();
                    }
                    if (retryHandle !== null) {
                        clearTimeout(retryHandle);
                        retryHandle = null;
                    }
                };
                var retryLoop = function (retryIndex) {
                    request.open('GET', loadUrl, true);
                    if (useArrayBuffer) {
                        request.responseType = "arraybuffer";
                    }
                    if (onProgress) {
                        request.addEventListener("progress", onProgress);
                    }
                    var onLoadEnd = function () {
                        request.removeEventListener("loadend", onLoadEnd);
                        fileRequest.onCompleteObservable.notifyObservers(fileRequest);
                        fileRequest.onCompleteObservable.clear();
                    };
                    request.addEventListener("loadend", onLoadEnd);
                    var onReadyStateChange = function () {
                        if (aborted) {
                            return;
                        }
                        // In case of undefined state in some browsers.
                        if (request.readyState === (XMLHttpRequest.DONE || 4)) {
                            // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
                            request.removeEventListener("readystatechange", onReadyStateChange);
                            if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
                                onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
                                return;
                            }
                            var retryStrategy = Tools.DefaultRetryStrategy;
                            if (retryStrategy) {
                                var waitTime = retryStrategy(loadUrl, request, retryIndex);
                                if (waitTime !== -1) {
                                    // Prevent the request from completing for retry.
                                    request.removeEventListener("loadend", onLoadEnd);
                                    request = new XMLHttpRequest();
                                    retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
                                    return;
                                }
                            }
                            var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
                            if (onError) {
                                onError(request, e);
                            }
                            else {
                                throw e;
                            }
                        }
                    };
                    request.addEventListener("readystatechange", onReadyStateChange);
                    request.send();
                };
                retryLoop(0);
            };
            // Caching all files
            if (database && database.enableSceneOffline) {
                var noIndexedDB_1 = function (request) {
                    if (request && request.status > 400) {
                        if (onError) {
                            onError(request);
                        }
                    }
                    else {
                        if (!aborted) {
                            requestFile();
                        }
                    }
                };
                var loadFromIndexedDB = function () {
                    // TODO: database needs to support aborting and should return a IFileRequest
                    if (aborted) {
                        return;
                    }
                    if (database) {
                        database.loadFileFromDB(url, function (data) {
                            if (!aborted) {
                                onSuccess(data);
                            }
                            fileRequest.onCompleteObservable.notifyObservers(fileRequest);
                        }, onProgress ? function (event) {
                            if (!aborted) {
                                onProgress(event);
                            }
                        } : undefined, noIndexedDB_1, useArrayBuffer);
                    }
                };
                database.openAsync(loadFromIndexedDB, noIndexedDB_1);
            }
            else {
                requestFile();
            }
            return fileRequest;
        };
        /**
         * Load a script (identified by an url). When the url returns, the
         * content of this file is added into a new script element, attached to the DOM (body element)
         * @param scriptUrl defines the url of the script to laod
         * @param onSuccess defines the callback called when the script is loaded
         * @param onError defines the callback to call if an error occurs
         */
        Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
            if (!Tools.IsWindowObjectExist()) {
                return;
            }
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = scriptUrl;
            script.onload = function () {
                if (onSuccess) {
                    onSuccess();
                }
            };
            script.onerror = function (e) {
                if (onError) {
                    onError("Unable to load script '" + scriptUrl + "'", e);
                }
            };
            head.appendChild(script);
        };
        /**
         * Loads a file from a blob
         * @param fileToLoad defines the blob to use
         * @param callback defines the callback to call when data is loaded
         * @param progressCallback defines the callback to call during loading process
         * @returns a file request object
         */
        Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
            var reader = new FileReader();
            var request = {
                onCompleteObservable: new BABYLON.Observable(),
                abort: function () { return reader.abort(); },
            };
            reader.onloadend = function (e) {
                request.onCompleteObservable.notifyObservers(request);
            };
            reader.onload = function (e) {
                //target doesn't have result from ts 1.3
                callback(e.target['result']);
            };
            reader.onprogress = progressCallback;
            reader.readAsDataURL(fileToLoad);
            return request;
        };
        /**
         * Loads a file
         * @param fileToLoad defines the file to load
         * @param callback defines the callback to call when data is loaded
         * @param progressCallBack defines the callback to call during loading process
         * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
         * @returns a file request object
         */
        Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
            var reader = new FileReader();
            var request = {
                onCompleteObservable: new BABYLON.Observable(),
                abort: function () { return reader.abort(); },
            };
            reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
            reader.onerror = function (e) {
                Tools.Log("Error while reading file: " + fileToLoad.name);
                callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
            };
            reader.onload = function (e) {
                //target doesn't have result from ts 1.3
                callback(e.target['result']);
            };
            if (progressCallBack) {
                reader.onprogress = progressCallBack;
            }
            if (!useArrayBuffer) {
                // Asynchronous read
                reader.readAsText(fileToLoad);
            }
            else {
                reader.readAsArrayBuffer(fileToLoad);
            }
            return request;
        };
        /**
         * Creates a data url from a given string content
         * @param content defines the content to convert
         * @returns the new data url link
         */
        Tools.FileAsURL = function (content) {
            var fileBlob = new Blob([content]);
            var url = window.URL || window.webkitURL;
            var link = url.createObjectURL(fileBlob);
            return link;
        };
        /**
         * Format the given number to a specific decimal format
         * @param value defines the number to format
         * @param decimals defines the number of decimals to use
         * @returns the formatted string
         */
        Tools.Format = function (value, decimals) {
            if (decimals === void 0) { decimals = 2; }
            return value.toFixed(decimals);
        };
        /**
         * Checks if a given vector is inside a specific range
         * @param v defines the vector to test
         * @param min defines the minimum range
         * @param max defines the maximum range
         */
        Tools.CheckExtends = function (v, min, max) {
            if (v.x < min.x) {
                min.x = v.x;
            }
            if (v.y < min.y) {
                min.y = v.y;
            }
            if (v.z < min.z) {
                min.z = v.z;
            }
            if (v.x > max.x) {
                max.x = v.x;
            }
            if (v.y > max.y) {
                max.y = v.y;
            }
            if (v.z > max.z) {
                max.z = v.z;
            }
        };
        /**
         * Tries to copy an object by duplicating every property
         * @param source defines the source object
         * @param destination defines the target object
         * @param doNotCopyList defines a list of properties to avoid
         * @param mustCopyList defines a list of properties to copy (even if they start with _)
         */
        Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
            for (var prop in source) {
                if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
                    continue;
                }
                if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
                    continue;
                }
                var sourceValue = source[prop];
                var typeOfSourceValue = typeof sourceValue;
                if (typeOfSourceValue === "function") {
                    continue;
                }
                try {
                    if (typeOfSourceValue === "object") {
                        if (sourceValue instanceof Array) {
                            destination[prop] = [];
                            if (sourceValue.length > 0) {
                                if (typeof sourceValue[0] == "object") {
                                    for (var index = 0; index < sourceValue.length; index++) {
                                        var clonedValue = cloneValue(sourceValue[index], destination);
                                        if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
                                            destination[prop].push(clonedValue);
                                        }
                                    }
                                }
                                else {
                                    destination[prop] = sourceValue.slice(0);
                                }
                            }
                        }
                        else {
                            destination[prop] = cloneValue(sourceValue, destination);
                        }
                    }
                    else {
                        destination[prop] = sourceValue;
                    }
                }
                catch (e) {
                    // Just ignore error (it could be because of a read-only property)
                }
            }
        };
        /**
         * Gets a boolean indicating if the given object has no own property
         * @param obj defines the object to test
         * @returns true if object has no own property
         */
        Tools.IsEmpty = function (obj) {
            for (var i in obj) {
                if (obj.hasOwnProperty(i)) {
                    return false;
                }
            }
            return true;
        };
        /**
         * Function used to register events at window level
         * @param events defines the events to register
         */
        Tools.RegisterTopRootEvents = function (events) {
            for (var index = 0; index < events.length; index++) {
                var event = events[index];
                window.addEventListener(event.name, event.handler, false);
                try {
                    if (window.parent) {
                        window.parent.addEventListener(event.name, event.handler, false);
                    }
                }
                catch (e) {
                    // Silently fails...
                }
            }
        };
        /**
         * Function used to unregister events from window level
         * @param events defines the events to unregister
         */
        Tools.UnregisterTopRootEvents = function (events) {
            for (var index = 0; index < events.length; index++) {
                var event = events[index];
                window.removeEventListener(event.name, event.handler);
                try {
                    if (window.parent) {
                        window.parent.removeEventListener(event.name, event.handler);
                    }
                }
                catch (e) {
                    // Silently fails...
                }
            }
        };
        /**
         * Dumps the current bound framebuffer
         * @param width defines the rendering width
         * @param height defines the rendering height
         * @param engine defines the hosting engine
         * @param successCallback defines the callback triggered once the data are available
         * @param mimeType defines the mime type of the result
         * @param fileName defines the filename to download. If present, the result will automatically be downloaded
         */
        Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            // Read the contents of the framebuffer
            var numberOfChannelsByLine = width * 4;
            var halfHeight = height / 2;
            //Reading datas from WebGL
            var data = engine.readPixels(0, 0, width, height);
            //To flip image on Y axis.
            for (var i = 0; i < halfHeight; i++) {
                for (var j = 0; j < numberOfChannelsByLine; j++) {
                    var currentCell = j + i * numberOfChannelsByLine;
                    var targetLine = height - i - 1;
                    var targetCell = j + targetLine * numberOfChannelsByLine;
                    var temp = data[currentCell];
                    data[currentCell] = data[targetCell];
                    data[targetCell] = temp;
                }
            }
            // Create a 2D canvas to store the result
            if (!screenshotCanvas) {
                screenshotCanvas = document.createElement('canvas');
            }
            screenshotCanvas.width = width;
            screenshotCanvas.height = height;
            var context = screenshotCanvas.getContext('2d');
            if (context) {
                // Copy the pixels to a 2D canvas
                var imageData = context.createImageData(width, height);
                var castData = (imageData.data);
                castData.set(data);
                context.putImageData(imageData, 0, 0);
                Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
            }
        };
        /**
         * Converts the canvas data to blob.
         * This acts as a polyfill for browsers not supporting the to blob function.
         * @param canvas Defines the canvas to extract the data from
         * @param successCallback Defines the callback triggered once the data are available
         * @param mimeType Defines the mime type of the result
         */
        Tools.ToBlob = function (canvas, successCallback, mimeType) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            // We need HTMLCanvasElement.toBlob for HD screenshots
            if (!canvas.toBlob) {
                //  low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
                canvas.toBlob = function (callback, type, quality) {
                    var _this = this;
                    setTimeout(function () {
                        var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
                        for (var i = 0; i < len; i++) {
                            arr[i] = binStr.charCodeAt(i);
                        }
                        callback(new Blob([arr]));
                    });
                };
            }
            canvas.toBlob(function (blob) {
                successCallback(blob);
            }, mimeType);
        };
        /**
         * Encodes the canvas data to base 64 or automatically download the result if filename is defined
         * @param successCallback defines the callback triggered once the data are available
         * @param mimeType defines the mime type of the result
         * @param fileName defines he filename to download. If present, the result will automatically be downloaded
         */
        Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            if (successCallback) {
                var base64Image = screenshotCanvas.toDataURL(mimeType);
                successCallback(base64Image);
            }
            else {
                this.ToBlob(screenshotCanvas, function (blob) {
                    //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
                    if (("download" in document.createElement("a"))) {
                        if (!fileName) {
                            var date = new Date();
                            var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
                            fileName = "screenshot_" + stringDate + ".png";
                        }
                        Tools.Download(blob, fileName);
                    }
                    else {
                        var url = URL.createObjectURL(blob);
                        var newWindow = window.open("");
                        if (!newWindow) {
                            return;
                        }
                        var img = newWindow.document.createElement("img");
                        img.onload = function () {
                            // no longer need to read the blob so it's revoked
                            URL.revokeObjectURL(url);
                        };
                        img.src = url;
                        newWindow.document.body.appendChild(img);
                    }
                }, mimeType);
            }
        };
        /**
         * Downloads a blob in the browser
         * @param blob defines the blob to download
         * @param fileName defines the name of the downloaded file
         */
        Tools.Download = function (blob, fileName) {
            if (navigator && navigator.msSaveBlob) {
                navigator.msSaveBlob(blob, fileName);
                return;
            }
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.style.display = "none";
            a.href = url;
            a.download = fileName;
            a.addEventListener("click", function () {
                if (a.parentElement) {
                    a.parentElement.removeChild(a);
                }
            });
            a.click();
            window.URL.revokeObjectURL(url);
        };
        /**
         * Captures a screenshot of the current rendering
         * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
         * @param engine defines the rendering engine
         * @param camera defines the source camera
         * @param size This parameter can be set to a single number or to an object with the
         * following (optional) properties: precision, width, height. If a single number is passed,
         * it will be used for both width and height. If an object is passed, the screenshot size
         * will be derived from the parameters. The precision property is a multiplier allowing
         * rendering at a higher or lower resolution
         * @param successCallback defines the callback receives a single parameter which contains the
         * screenshot as a string of base64-encoded characters. This string can be assigned to the
         * src parameter of an <img> to display it
         * @param mimeType defines the MIME type of the screenshot image (default: image/png).
         * Check your browser for supported MIME types
         */
        Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            var width;
            var height;
            // If a precision value is specified
            if (size.precision) {
                width = Math.round(engine.getRenderWidth() * size.precision);
                height = Math.round(width / engine.getAspectRatio(camera));
            }
            else if (size.width && size.height) {
                width = size.width;
                height = size.height;
            }
            //If passing only width, computing height to keep display canvas ratio.
            else if (size.width && !size.height) {
                width = size.width;
                height = Math.round(width / engine.getAspectRatio(camera));
            }
            //If passing only height, computing width to keep display canvas ratio.
            else if (size.height && !size.width) {
                height = size.height;
                width = Math.round(height * engine.getAspectRatio(camera));
            }
            //Assuming here that "size" parameter is a number
            else if (!isNaN(size)) {
                height = size;
                width = size;
            }
            else {
                Tools.Error("Invalid 'size' parameter !");
                return;
            }
            if (!screenshotCanvas) {
                screenshotCanvas = document.createElement('canvas');
            }
            screenshotCanvas.width = width;
            screenshotCanvas.height = height;
            var renderContext = screenshotCanvas.getContext("2d");
            var ratio = engine.getRenderWidth() / engine.getRenderHeight();
            var newWidth = width;
            var newHeight = newWidth / ratio;
            if (newHeight > height) {
                newHeight = height;
                newWidth = newHeight * ratio;
            }
            var offsetX = Math.max(0, width - newWidth) / 2;
            var offsetY = Math.max(0, height - newHeight) / 2;
            var renderingCanvas = engine.getRenderingCanvas();
            if (renderContext && renderingCanvas) {
                renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
            }
            Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
        };
        /**
         * Generates an image screenshot from the specified camera.
         * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
         * @param engine The engine to use for rendering
         * @param camera The camera to use for rendering
         * @param size This parameter can be set to a single number or to an object with the
         * following (optional) properties: precision, width, height. If a single number is passed,
         * it will be used for both width and height. If an object is passed, the screenshot size
         * will be derived from the parameters. The precision property is a multiplier allowing
         * rendering at a higher or lower resolution
         * @param successCallback The callback receives a single parameter which contains the
         * screenshot as a string of base64-encoded characters. This string can be assigned to the
         * src parameter of an <img> to display it
         * @param mimeType The MIME type of the screenshot image (default: image/png).
         * Check your browser for supported MIME types
         * @param samples Texture samples (default: 1)
         * @param antialiasing Whether antialiasing should be turned on or not (default: false)
         * @param fileName A name for for the downloaded file.
         */
        Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
            if (mimeType === void 0) { mimeType = "image/png"; }
            if (samples === void 0) { samples = 1; }
            if (antialiasing === void 0) { antialiasing = false; }
            var width;
            var height;
            //If a precision value is specified
            if (size.precision) {
                width = Math.round(engine.getRenderWidth() * size.precision);
                height = Math.round(width / engine.getAspectRatio(camera));
                size = { width: width, height: height };
            }
            else if (size.width && size.height) {
                width = size.width;
                height = size.height;
            }
            //If passing only width, computing height to keep display canvas ratio.
            else if (size.width && !size.height) {
                width = size.width;
                height = Math.round(width / engine.getAspectRatio(camera));
                size = { width: width, height: height };
            }
            //If passing only height, computing width to keep display canvas ratio.
            else if (size.height && !size.width) {
                height = size.height;
                width = Math.round(height * engine.getAspectRatio(camera));
                size = { width: width, height: height };
            }
            //Assuming here that "size" parameter is a number
            else if (!isNaN(size)) {
                height = size;
                width = size;
            }
            else {
                Tools.Error("Invalid 'size' parameter !");
                return;
            }
            var scene = camera.getScene();
            var previousCamera = null;
            if (scene.activeCamera !== camera) {
                previousCamera = scene.activeCamera;
                scene.activeCamera = camera;
            }
            // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
            var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
            texture.renderList = null;
            texture.samples = samples;
            if (antialiasing) {
                texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
            }
            texture.onAfterRenderObservable.add(function () {
                Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
            });
            scene.incrementRenderId();
            scene.resetCachedMaterial();
            texture.render(true);
            texture.dispose();
            if (previousCamera) {
                scene.activeCamera = previousCamera;
            }
            camera.getProjectionMatrix(true); // Force cache refresh;
        };
        /**
         * Validates if xhr data is correct
         * @param xhr defines the request to validate
         * @param dataType defines the expected data type
         * @returns true if data is correct
         */
        Tools.ValidateXHRData = function (xhr, dataType) {
            // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
            if (dataType === void 0) { dataType = 7; }
            try {
                if (dataType & 1) {
                    if (xhr.responseText && xhr.responseText.length > 0) {
                        return true;
                    }
                    else if (dataType === 1) {
                        return false;
                    }
                }
                if (dataType & 2) {
                    // Check header width and height since there is no "TGA" magic number
                    var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
                    if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
                        return true;
                    }
                    else if (dataType === 2) {
                        return false;
                    }
                }
                if (dataType & 4) {
                    // Check for the "DDS" magic number
                    var ddsHeader = new Uint8Array(xhr.response, 0, 3);
                    if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
                        return true;
                    }
                    else {
                        return false;
                    }
                }
            }
            catch (e) {
                // Global protection
            }
            return false;
        };
        /**
         * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
         * Be aware Math.random() could cause collisions, but:
         * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
         * @returns a pseudo random id
         */
        Tools.RandomId = function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        };
        /**
        * Test if the given uri is a base64 string
        * @param uri The uri to test
        * @return True if the uri is a base64 string or false otherwise
        */
        Tools.IsBase64 = function (uri) {
            return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
        };
        /**
        * Decode the given base64 uri.
        * @param uri The uri to decode
        * @return The decoded base64 data.
        */
        Tools.DecodeBase64 = function (uri) {
            var decodedString = atob(uri.split(",")[1]);
            var bufferLength = decodedString.length;
            var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
            for (var i = 0; i < bufferLength; i++) {
                bufferView[i] = decodedString.charCodeAt(i);
            }
            return bufferView.buffer;
        };
        Tools._AddLogEntry = function (entry) {
            Tools._LogCache = entry + Tools._LogCache;
            if (Tools.OnNewCacheEntry) {
                Tools.OnNewCacheEntry(entry);
            }
        };
        Tools._FormatMessage = function (message) {
            var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
            var date = new Date();
            return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
        };
        Tools._LogDisabled = function (message) {
            // nothing to do
        };
        Tools._LogEnabled = function (message) {
            var formattedMessage = Tools._FormatMessage(message);
            console.log("BJS - " + formattedMessage);
            var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
            Tools._AddLogEntry(entry);
        };
        Tools._WarnDisabled = function (message) {
            // nothing to do
        };
        Tools._WarnEnabled = function (message) {
            var formattedMessage = Tools._FormatMessage(message);
            console.warn("BJS - " + formattedMessage);
            var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
            Tools._AddLogEntry(entry);
        };
        Tools._ErrorDisabled = function (message) {
            // nothing to do
        };
        Tools._ErrorEnabled = function (message) {
            Tools.errorsCount++;
            var formattedMessage = Tools._FormatMessage(message);
            console.error("BJS - " + formattedMessage);
            var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
            Tools._AddLogEntry(entry);
        };
        Object.defineProperty(Tools, "LogCache", {
            /**
             * Gets current log cache (list of logs)
             */
            get: function () {
                return Tools._LogCache;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Clears the log cache
         */
        Tools.ClearLogCache = function () {
            Tools._LogCache = "";
            Tools.errorsCount = 0;
        };
        Object.defineProperty(Tools, "LogLevels", {
            /**
             * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
             */
            set: function (level) {
                if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
                    Tools.Log = Tools._LogEnabled;
                }
                else {
                    Tools.Log = Tools._LogDisabled;
                }
                if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
                    Tools.Warn = Tools._WarnEnabled;
                }
                else {
                    Tools.Warn = Tools._WarnDisabled;
                }
                if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
                    Tools.Error = Tools._ErrorEnabled;
                }
                else {
                    Tools.Error = Tools._ErrorDisabled;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Checks if the loaded document was accessed via `file:`-Protocol.
         * @returns boolean
         */
        Tools.IsFileURL = function () {
            return location.protocol === "file:";
        };
        /**
         * Checks if the window object exists
         * @returns true if the window object exists
         */
        Tools.IsWindowObjectExist = function () {
            return (typeof window) !== "undefined";
        };
        Object.defineProperty(Tools, "PerformanceLogLevel", {
            /**
             * Sets the current performance log level
             */
            set: function (level) {
                if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
                    Tools.StartPerformanceCounter = Tools._StartUserMark;
                    Tools.EndPerformanceCounter = Tools._EndUserMark;
                    return;
                }
                if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
                    Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
                    Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
                    return;
                }
                Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
                Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
            },
            enumerable: true,
            configurable: true
        });
        Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
        };
        Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
        };
        Tools._StartUserMark = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!Tools._performance) {
                if (!Tools.IsWindowObjectExist()) {
                    return;
                }
                Tools._performance = window.performance;
            }
            if (!condition || !Tools._performance.mark) {
                return;
            }
            Tools._performance.mark(counterName + "-Begin");
        };
        Tools._EndUserMark = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition || !Tools._performance.mark) {
                return;
            }
            Tools._performance.mark(counterName + "-End");
            Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
        };
        Tools._StartPerformanceConsole = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition) {
                return;
            }
            Tools._StartUserMark(counterName, condition);
            if (console.time) {
                console.time(counterName);
            }
        };
        Tools._EndPerformanceConsole = function (counterName, condition) {
            if (condition === void 0) { condition = true; }
            if (!condition) {
                return;
            }
            Tools._EndUserMark(counterName, condition);
            if (console.time) {
                console.timeEnd(counterName);
            }
        };
        Object.defineProperty(Tools, "Now", {
            /**
             * Gets either window.performance.now() if supported or Date.now() else
             */
            get: function () {
                if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
                    return window.performance.now();
                }
                return Date.now();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * This method will return the name of the class used to create the instance of the given object.
         * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
         * @param object the object to get the class name from
         * @param isType defines if the object is actually a type
         * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
         */
        Tools.GetClassName = function (object, isType) {
            if (isType === void 0) { isType = false; }
            var name = null;
            if (!isType && object.getClassName) {
                name = object.getClassName();
            }
            else {
                if (object instanceof Object) {
                    var classObj = isType ? object : Object.getPrototypeOf(object);
                    name = classObj.constructor["__bjsclassName__"];
                }
                if (!name) {
                    name = typeof object;
                }
            }
            return name;
        };
        /**
         * Gets the first element of an array satisfying a given predicate
         * @param array defines the array to browse
         * @param predicate defines the predicate to use
         * @returns null if not found or the element
         */
        Tools.First = function (array, predicate) {
            for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
                var el = array_1[_i];
                if (predicate(el)) {
                    return el;
                }
            }
            return null;
        };
        /**
         * This method will return the name of the full name of the class, including its owning module (if any).
         * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
         * @param object the object to get the class name from
         * @param isType defines if the object is actually a type
         * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
         * @ignorenaming
         */
        Tools.getFullClassName = function (object, isType) {
            if (isType === void 0) { isType = false; }
            var className = null;
            var moduleName = null;
            if (!isType && object.getClassName) {
                className = object.getClassName();
            }
            else {
                if (object instanceof Object) {
                    var classObj = isType ? object : Object.getPrototypeOf(object);
                    className = classObj.constructor["__bjsclassName__"];
                    moduleName = classObj.constructor["__bjsmoduleName__"];
                }
                if (!className) {
                    className = typeof object;
                }
            }
            if (!className) {
                return null;
            }
            return ((moduleName != null) ? (moduleName + ".") : "") + className;
        };
        /**
         * Returns a promise that resolves after the given amount of time.
         * @param delay Number of milliseconds to delay
         * @returns Promise that resolves after the given amount of time
         */
        Tools.DelayAsync = function (delay) {
            return new Promise(function (resolve) {
                setTimeout(function () {
                    resolve();
                }, delay);
            });
        };
        /**
         * Gets the current gradient from an array of IValueGradient
         * @param ratio defines the current ratio to get
         * @param gradients defines the array of IValueGradient
         * @param updateFunc defines the callback function used to get the final value from the selected gradients
         */
        Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
            for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
                var currentGradient = gradients[gradientIndex];
                var nextGradient = gradients[gradientIndex + 1];
                if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
                    var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
                    updateFunc(currentGradient, nextGradient, scale);
                    return;
                }
            }
            // Use last index if over
            var lastIndex = gradients.length - 1;
            updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
        };
        /**
         * Gets or sets the base URL to use to load assets
         */
        Tools.BaseUrl = "";
        /**
         * Gets or sets the retry strategy to apply when an error happens while loading an asset
         */
        Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
        /**
         * Default behaviour for cors in the application.
         * It can be a string if the expected behavior is identical in the entire app.
         * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
         */
        Tools.CorsBehavior = "anonymous";
        /**
         * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
         * @ignorenaming
         */
        Tools.UseFallbackTexture = true;
        /**
         * Use this object to register external classes like custom textures or material
         * to allow the laoders to instantiate them
         */
        Tools.RegisteredExternalClasses = {};
        /**
         * Texture content used if a texture cannot loaded
         * @ignorenaming
         */
        Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
        Tools._tmpFloatArray = new Float32Array(1);
        /**
         * Gets or sets a function used to pre-process url before using them to load assets
         */
        Tools.PreprocessUrl = function (url) {
            return url;
        };
        // Logs
        /**
         * No log
         */
        Tools.NoneLogLevel = 0;
        /**
         * Only message logs
         */
        Tools.MessageLogLevel = 1;
        /**
         * Only warning logs
         */
        Tools.WarningLogLevel = 2;
        /**
         * Only error logs
         */
        Tools.ErrorLogLevel = 4;
        /**
         * All logs
         */
        Tools.AllLogLevel = 7;
        Tools._LogCache = "";
        /**
         * Gets a value indicating the number of loading errors
         * @ignorenaming
         */
        Tools.errorsCount = 0;
        /**
         * Log a message to the console
         */
        Tools.Log = Tools._LogEnabled;
        /**
         * Write a warning message to the console
         */
        Tools.Warn = Tools._WarnEnabled;
        /**
         * Write an error message to the console
         */
        Tools.Error = Tools._ErrorEnabled;
        // Performances
        /**
         * No performance log
         */
        Tools.PerformanceNoneLogLevel = 0;
        /**
         * Use user marks to log performance
         */
        Tools.PerformanceUserMarkLogLevel = 1;
        /**
         * Log performance to the console
         */
        Tools.PerformanceConsoleLogLevel = 2;
        /**
         * Starts a performance counter
         */
        Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
        /**
         * Ends a specific performance coutner
         */
        Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
        return Tools;
    }());
    BABYLON.Tools = Tools;
    /**
     * This class is used to track a performance counter which is number based.
     * The user has access to many properties which give statistics of different nature.
     *
     * The implementer can track two kinds of Performance Counter: time and count.
     * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
     * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
     */
    var PerfCounter = /** @class */ (function () {
        /**
         * Creates a new counter
         */
        function PerfCounter() {
            this._startMonitoringTime = 0;
            this._min = 0;
            this._max = 0;
            this._average = 0;
            this._lastSecAverage = 0;
            this._current = 0;
            this._totalValueCount = 0;
            this._totalAccumulated = 0;
            this._lastSecAccumulated = 0;
            this._lastSecTime = 0;
            this._lastSecValueCount = 0;
        }
        Object.defineProperty(PerfCounter.prototype, "min", {
            /**
             * Returns the smallest value ever
             */
            get: function () {
                return this._min;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "max", {
            /**
             * Returns the biggest value ever
             */
            get: function () {
                return this._max;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "average", {
            /**
             * Returns the average value since the performance counter is running
             */
            get: function () {
                return this._average;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
            /**
             * Returns the average value of the last second the counter was monitored
             */
            get: function () {
                return this._lastSecAverage;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "current", {
            /**
             * Returns the current value
             */
            get: function () {
                return this._current;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "total", {
            /**
             * Gets the accumulated total
             */
            get: function () {
                return this._totalAccumulated;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerfCounter.prototype, "count", {
            /**
             * Gets the total value count
             */
            get: function () {
                return this._totalValueCount;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Call this method to start monitoring a new frame.
         * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
         */
        PerfCounter.prototype.fetchNewFrame = function () {
            this._totalValueCount++;
            this._current = 0;
            this._lastSecValueCount++;
        };
        /**
         * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
         * @param newCount the count value to add to the monitored count
         * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
         */
        PerfCounter.prototype.addCount = function (newCount, fetchResult) {
            if (!PerfCounter.Enabled) {
                return;
            }
            this._current += newCount;
            if (fetchResult) {
                this._fetchResult();
            }
        };
        /**
         * Start monitoring this performance counter
         */
        PerfCounter.prototype.beginMonitoring = function () {
            if (!PerfCounter.Enabled) {
                return;
            }
            this._startMonitoringTime = Tools.Now;
        };
        /**
         * Compute the time lapsed since the previous beginMonitoring() call.
         * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
         */
        PerfCounter.prototype.endMonitoring = function (newFrame) {
            if (newFrame === void 0) { newFrame = true; }
            if (!PerfCounter.Enabled) {
                return;
            }
            if (newFrame) {
                this.fetchNewFrame();
            }
            var currentTime = Tools.Now;
            this._current = currentTime - this._startMonitoringTime;
            if (newFrame) {
                this._fetchResult();
            }
        };
        PerfCounter.prototype._fetchResult = function () {
            this._totalAccumulated += this._current;
            this._lastSecAccumulated += this._current;
            // Min/Max update
            this._min = Math.min(this._min, this._current);
            this._max = Math.max(this._max, this._current);
            this._average = this._totalAccumulated / this._totalValueCount;
            // Reset last sec?
            var now = Tools.Now;
            if ((now - this._lastSecTime) > 1000) {
                this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
                this._lastSecTime = now;
                this._lastSecAccumulated = 0;
                this._lastSecValueCount = 0;
            }
        };
        /**
         * Gets or sets a global boolean to turn on and off all the counters
         */
        PerfCounter.Enabled = true;
        return PerfCounter;
    }());
    BABYLON.PerfCounter = PerfCounter;
    /**
     * Use this className as a decorator on a given class definition to add it a name and optionally its module.
     * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
     * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
     * @param name The name of the class, case should be preserved
     * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
     */
    function className(name, module) {
        return function (target) {
            target["__bjsclassName__"] = name;
            target["__bjsmoduleName__"] = (module != null) ? module : null;
        };
    }
    BABYLON.className = className;
    /**
     * An implementation of a loop for asynchronous functions.
     */
    var AsyncLoop = /** @class */ (function () {
        /**
         * Constructor.
         * @param iterations the number of iterations.
         * @param func the function to run each iteration
         * @param successCallback the callback that will be called upon succesful execution
         * @param offset starting offset.
         */
        function AsyncLoop(
        /**
         * Defines the number of iterations for the loop
         */
        iterations, func, successCallback, offset) {
            if (offset === void 0) { offset = 0; }
            this.iterations = iterations;
            this.index = offset - 1;
            this._done = false;
            this._fn = func;
            this._successCallback = successCallback;
        }
        /**
         * Execute the next iteration. Must be called after the last iteration was finished.
         */
        AsyncLoop.prototype.executeNext = function () {
            if (!this._done) {
                if (this.index + 1 < this.iterations) {
                    ++this.index;
                    this._fn(this);
                }
                else {
                    this.breakLoop();
                }
            }
        };
        /**
         * Break the loop and run the success callback.
         */
        AsyncLoop.prototype.breakLoop = function () {
            this._done = true;
            this._successCallback();
        };
        /**
         * Create and run an async loop.
         * @param iterations the number of iterations.
         * @param fn the function to run each iteration
         * @param successCallback the callback that will be called upon succesful execution
         * @param offset starting offset.
         * @returns the created async loop object
         */
        AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
            if (offset === void 0) { offset = 0; }
            var loop = new AsyncLoop(iterations, fn, successCallback, offset);
            loop.executeNext();
            return loop;
        };
        /**
         * A for-loop that will run a given number of iterations synchronous and the rest async.
         * @param iterations total number of iterations
         * @param syncedIterations number of synchronous iterations in each async iteration.
         * @param fn the function to call each iteration.
         * @param callback a success call back that will be called when iterating stops.
         * @param breakFunction a break condition (optional)
         * @param timeout timeout settings for the setTimeout function. default - 0.
         * @returns the created async loop object
         */
        AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
            if (timeout === void 0) { timeout = 0; }
            return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
                if (breakFunction && breakFunction()) {
                    loop.breakLoop();
                }
                else {
                    setTimeout(function () {
                        for (var i = 0; i < syncedIterations; ++i) {
                            var iteration = (loop.index * syncedIterations) + i;
                            if (iteration >= iterations) {
                                break;
                            }
                            fn(iteration);
                            if (breakFunction && breakFunction()) {
                                loop.breakLoop();
                                break;
                            }
                        }
                        loop.executeNext();
                    }, timeout);
                }
            }, callback);
        };
        return AsyncLoop;
    }());
    BABYLON.AsyncLoop = AsyncLoop;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.tools.js.map

var BABYLON;
(function (BABYLON) {
    var PromiseStates;
    (function (PromiseStates) {
        PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
        PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
        PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
    })(PromiseStates || (PromiseStates = {}));
    var FulFillmentAgregator = /** @class */ (function () {
        function FulFillmentAgregator() {
            this.count = 0;
            this.target = 0;
            this.results = [];
        }
        return FulFillmentAgregator;
    }());
    var InternalPromise = /** @class */ (function () {
        function InternalPromise(resolver) {
            var _this = this;
            this._state = PromiseStates.Pending;
            this._children = new Array();
            this._rejectWasConsumed = false;
            if (!resolver) {
                return;
            }
            try {
                resolver(function (value) {
                    _this._resolve(value);
                }, function (reason) {
                    _this._reject(reason);
                });
            }
            catch (e) {
                this._reject(e);
            }
        }
        Object.defineProperty(InternalPromise.prototype, "_result", {
            get: function () {
                return this._resultValue;
            },
            set: function (value) {
                this._resultValue = value;
                if (this._parent && this._parent._result === undefined) {
                    this._parent._result = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        InternalPromise.prototype.catch = function (onRejected) {
            return this.then(undefined, onRejected);
        };
        InternalPromise.prototype.then = function (onFulfilled, onRejected) {
            var _this = this;
            var newPromise = new InternalPromise();
            newPromise._onFulfilled = onFulfilled;
            newPromise._onRejected = onRejected;
            // Composition
            this._children.push(newPromise);
            newPromise._parent = this;
            if (this._state !== PromiseStates.Pending) {
                BABYLON.Tools.SetImmediate(function () {
                    if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
                        var returnedValue = newPromise._resolve(_this._result);
                        if (returnedValue !== undefined && returnedValue !== null) {
                            if (returnedValue._state !== undefined) {
                                var returnedPromise = returnedValue;
                                newPromise._children.push(returnedPromise);
                                returnedPromise._parent = newPromise;
                                newPromise = returnedPromise;
                            }
                            else {
                                newPromise._result = returnedValue;
                            }
                        }
                    }
                    else {
                        newPromise._reject(_this._reason);
                    }
                });
            }
            return newPromise;
        };
        InternalPromise.prototype._moveChildren = function (children) {
            var _this = this;
            var _a;
            (_a = this._children).push.apply(_a, children.splice(0, children.length));
            this._children.forEach(function (child) {
                child._parent = _this;
            });
            if (this._state === PromiseStates.Fulfilled) {
                for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
                    var child = _b[_i];
                    child._resolve(this._result);
                }
            }
            else if (this._state === PromiseStates.Rejected) {
                for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
                    var child = _d[_c];
                    child._reject(this._reason);
                }
            }
        };
        InternalPromise.prototype._resolve = function (value) {
            try {
                this._state = PromiseStates.Fulfilled;
                var returnedValue = null;
                if (this._onFulfilled) {
                    returnedValue = this._onFulfilled(value);
                }
                if (returnedValue !== undefined && returnedValue !== null) {
                    if (returnedValue._state !== undefined) {
                        // Transmit children
                        var returnedPromise = returnedValue;
                        returnedPromise._parent = this;
                        returnedPromise._moveChildren(this._children);
                        value = returnedPromise._result;
                    }
                    else {
                        value = returnedValue;
                    }
                }
                this._result = value;
                for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
                    var child = _a[_i];
                    child._resolve(value);
                }
                this._children.length = 0;
                delete this._onFulfilled;
                delete this._onRejected;
            }
            catch (e) {
                this._reject(e, true);
            }
        };
        InternalPromise.prototype._reject = function (reason, onLocalThrow) {
            if (onLocalThrow === void 0) { onLocalThrow = false; }
            this._state = PromiseStates.Rejected;
            this._reason = reason;
            if (this._onRejected && !onLocalThrow) {
                try {
                    this._onRejected(reason);
                    this._rejectWasConsumed = true;
                }
                catch (e) {
                    reason = e;
                }
            }
            for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
                var child = _a[_i];
                if (this._rejectWasConsumed) {
                    child._resolve(null);
                }
                else {
                    child._reject(reason);
                }
            }
            this._children.length = 0;
            delete this._onFulfilled;
            delete this._onRejected;
        };
        InternalPromise.resolve = function (value) {
            var newPromise = new InternalPromise();
            newPromise._resolve(value);
            return newPromise;
        };
        InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
            promise.then(function (value) {
                agregator.results[index] = value;
                agregator.count++;
                if (agregator.count === agregator.target) {
                    agregator.rootPromise._resolve(agregator.results);
                }
                return null;
            }, function (reason) {
                if (agregator.rootPromise._state !== PromiseStates.Rejected) {
                    agregator.rootPromise._reject(reason);
                }
            });
        };
        InternalPromise.all = function (promises) {
            var newPromise = new InternalPromise();
            var agregator = new FulFillmentAgregator();
            agregator.target = promises.length;
            agregator.rootPromise = newPromise;
            if (promises.length) {
                for (var index = 0; index < promises.length; index++) {
                    InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
                }
            }
            else {
                newPromise._resolve([]);
            }
            return newPromise;
        };
        InternalPromise.race = function (promises) {
            var newPromise = new InternalPromise();
            if (promises.length) {
                for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
                    var promise = promises_1[_i];
                    promise.then(function (value) {
                        if (newPromise) {
                            newPromise._resolve(value);
                            newPromise = null;
                        }
                        return null;
                    }, function (reason) {
                        if (newPromise) {
                            newPromise._reject(reason);
                            newPromise = null;
                        }
                    });
                }
            }
            return newPromise;
        };
        return InternalPromise;
    }());
    /**
     * Helper class that provides a small promise polyfill
     */
    var PromisePolyfill = /** @class */ (function () {
        function PromisePolyfill() {
        }
        /**
         * Static function used to check if the polyfill is required
         * If this is the case then the function will inject the polyfill to window.Promise
         * @param force defines a boolean used to force the injection (mostly for testing purposes)
         */
        PromisePolyfill.Apply = function (force) {
            if (force === void 0) { force = false; }
            if (force || typeof Promise === 'undefined') {
                var root = window;
                root.Promise = InternalPromise;
            }
        };
        return PromisePolyfill;
    }());
    BABYLON.PromisePolyfill = PromisePolyfill;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.promise.js.map

/// <reference path="../../../dist/preview release/babylon.d.ts" />
var BABYLON;
(function (BABYLON) {
    /**
     * Helper class to push actions to a pool of workers.
     */
    var WorkerPool = /** @class */ (function () {
        /**
         * Constructor
         * @param workers Array of workers to use for actions
         */
        function WorkerPool(workers) {
            this._pendingActions = new Array();
            this._workerInfos = workers.map(function (worker) { return ({
                worker: worker,
                active: false
            }); });
        }
        /**
         * Terminates all workers and clears any pending actions.
         */
        WorkerPool.prototype.dispose = function () {
            for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
                var workerInfo = _a[_i];
                workerInfo.worker.terminate();
            }
            delete this._workerInfos;
            delete this._pendingActions;
        };
        /**
         * Pushes an action to the worker pool. If all the workers are active, the action will be
         * pended until a worker has completed its action.
         * @param action The action to perform. Call onComplete when the action is complete.
         */
        WorkerPool.prototype.push = function (action) {
            for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
                var workerInfo = _a[_i];
                if (!workerInfo.active) {
                    this._execute(workerInfo, action);
                    return;
                }
            }
            this._pendingActions.push(action);
        };
        WorkerPool.prototype._execute = function (workerInfo, action) {
            var _this = this;
            workerInfo.active = true;
            action(workerInfo.worker, function () {
                workerInfo.active = false;
                var nextAction = _this._pendingActions.shift();
                if (nextAction) {
                    _this._execute(workerInfo, nextAction);
                }
            });
        };
        return WorkerPool;
    }());
    BABYLON.WorkerPool = WorkerPool;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.workerPool.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     **/
    var _AlphaState = /** @class */ (function () {
        /**
         * Initializes the state.
         */
        function _AlphaState() {
            this._isAlphaBlendDirty = false;
            this._isBlendFunctionParametersDirty = false;
            this._isBlendEquationParametersDirty = false;
            this._isBlendConstantsDirty = false;
            this._alphaBlend = false;
            this._blendFunctionParameters = new Array(4);
            this._blendEquationParameters = new Array(2);
            this._blendConstants = new Array(4);
            this.reset();
        }
        Object.defineProperty(_AlphaState.prototype, "isDirty", {
            get: function () {
                return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
            get: function () {
                return this._alphaBlend;
            },
            set: function (value) {
                if (this._alphaBlend === value) {
                    return;
                }
                this._alphaBlend = value;
                this._isAlphaBlendDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
            if (this._blendConstants[0] === r &&
                this._blendConstants[1] === g &&
                this._blendConstants[2] === b &&
                this._blendConstants[3] === a) {
                return;
            }
            this._blendConstants[0] = r;
            this._blendConstants[1] = g;
            this._blendConstants[2] = b;
            this._blendConstants[3] = a;
            this._isBlendConstantsDirty = true;
        };
        _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
            if (this._blendFunctionParameters[0] === value0 &&
                this._blendFunctionParameters[1] === value1 &&
                this._blendFunctionParameters[2] === value2 &&
                this._blendFunctionParameters[3] === value3) {
                return;
            }
            this._blendFunctionParameters[0] = value0;
            this._blendFunctionParameters[1] = value1;
            this._blendFunctionParameters[2] = value2;
            this._blendFunctionParameters[3] = value3;
            this._isBlendFunctionParametersDirty = true;
        };
        _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
            if (this._blendEquationParameters[0] === rgb &&
                this._blendEquationParameters[1] === alpha) {
                return;
            }
            this._blendEquationParameters[0] = rgb;
            this._blendEquationParameters[1] = alpha;
            this._isBlendEquationParametersDirty = true;
        };
        _AlphaState.prototype.reset = function () {
            this._alphaBlend = false;
            this._blendFunctionParameters[0] = null;
            this._blendFunctionParameters[1] = null;
            this._blendFunctionParameters[2] = null;
            this._blendFunctionParameters[3] = null;
            this._blendEquationParameters[0] = null;
            this._blendEquationParameters[1] = null;
            this._blendConstants[0] = null;
            this._blendConstants[1] = null;
            this._blendConstants[2] = null;
            this._blendConstants[3] = null;
            this._isAlphaBlendDirty = true;
            this._isBlendFunctionParametersDirty = false;
            this._isBlendEquationParametersDirty = false;
            this._isBlendConstantsDirty = false;
        };
        _AlphaState.prototype.apply = function (gl) {
            if (!this.isDirty) {
                return;
            }
            // Alpha blend
            if (this._isAlphaBlendDirty) {
                if (this._alphaBlend) {
                    gl.enable(gl.BLEND);
                }
                else {
                    gl.disable(gl.BLEND);
                }
                this._isAlphaBlendDirty = false;
            }
            // Alpha function
            if (this._isBlendFunctionParametersDirty) {
                gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
                this._isBlendFunctionParametersDirty = false;
            }
            // Alpha equation
            if (this._isBlendEquationParametersDirty) {
                gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
                this._isBlendEquationParametersDirty = false;
            }
            // Constants
            if (this._isBlendConstantsDirty) {
                gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
                this._isBlendConstantsDirty = false;
            }
        };
        return _AlphaState;
    }());
    BABYLON._AlphaState = _AlphaState;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.alphaCullingState.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     **/
    var _DepthCullingState = /** @class */ (function () {
        /**
         * Initializes the state.
         */
        function _DepthCullingState() {
            this._isDepthTestDirty = false;
            this._isDepthMaskDirty = false;
            this._isDepthFuncDirty = false;
            this._isCullFaceDirty = false;
            this._isCullDirty = false;
            this._isZOffsetDirty = false;
            this._isFrontFaceDirty = false;
            this.reset();
        }
        Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
            get: function () {
                return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
            get: function () {
                return this._zOffset;
            },
            set: function (value) {
                if (this._zOffset === value) {
                    return;
                }
                this._zOffset = value;
                this._isZOffsetDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
            get: function () {
                return this._cullFace;
            },
            set: function (value) {
                if (this._cullFace === value) {
                    return;
                }
                this._cullFace = value;
                this._isCullFaceDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "cull", {
            get: function () {
                return this._cull;
            },
            set: function (value) {
                if (this._cull === value) {
                    return;
                }
                this._cull = value;
                this._isCullDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
            get: function () {
                return this._depthFunc;
            },
            set: function (value) {
                if (this._depthFunc === value) {
                    return;
                }
                this._depthFunc = value;
                this._isDepthFuncDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
            get: function () {
                return this._depthMask;
            },
            set: function (value) {
                if (this._depthMask === value) {
                    return;
                }
                this._depthMask = value;
                this._isDepthMaskDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
            get: function () {
                return this._depthTest;
            },
            set: function (value) {
                if (this._depthTest === value) {
                    return;
                }
                this._depthTest = value;
                this._isDepthTestDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
            get: function () {
                return this._frontFace;
            },
            set: function (value) {
                if (this._frontFace === value) {
                    return;
                }
                this._frontFace = value;
                this._isFrontFaceDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        _DepthCullingState.prototype.reset = function () {
            this._depthMask = true;
            this._depthTest = true;
            this._depthFunc = null;
            this._cullFace = null;
            this._cull = null;
            this._zOffset = 0;
            this._frontFace = null;
            this._isDepthTestDirty = true;
            this._isDepthMaskDirty = true;
            this._isDepthFuncDirty = false;
            this._isCullFaceDirty = false;
            this._isCullDirty = false;
            this._isZOffsetDirty = false;
            this._isFrontFaceDirty = false;
        };
        _DepthCullingState.prototype.apply = function (gl) {
            if (!this.isDirty) {
                return;
            }
            // Cull
            if (this._isCullDirty) {
                if (this.cull) {
                    gl.enable(gl.CULL_FACE);
                }
                else {
                    gl.disable(gl.CULL_FACE);
                }
                this._isCullDirty = false;
            }
            // Cull face
            if (this._isCullFaceDirty) {
                gl.cullFace(this.cullFace);
                this._isCullFaceDirty = false;
            }
            // Depth mask
            if (this._isDepthMaskDirty) {
                gl.depthMask(this.depthMask);
                this._isDepthMaskDirty = false;
            }
            // Depth test
            if (this._isDepthTestDirty) {
                if (this.depthTest) {
                    gl.enable(gl.DEPTH_TEST);
                }
                else {
                    gl.disable(gl.DEPTH_TEST);
                }
                this._isDepthTestDirty = false;
            }
            // Depth func
            if (this._isDepthFuncDirty) {
                gl.depthFunc(this.depthFunc);
                this._isDepthFuncDirty = false;
            }
            // zOffset
            if (this._isZOffsetDirty) {
                if (this.zOffset) {
                    gl.enable(gl.POLYGON_OFFSET_FILL);
                    gl.polygonOffset(this.zOffset, 0);
                }
                else {
                    gl.disable(gl.POLYGON_OFFSET_FILL);
                }
                this._isZOffsetDirty = false;
            }
            // Front face
            if (this._isFrontFaceDirty) {
                gl.frontFace(this.frontFace);
                this._isFrontFaceDirty = false;
            }
        };
        return _DepthCullingState;
    }());
    BABYLON._DepthCullingState = _DepthCullingState;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.depthCullingState.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     **/
    var _StencilState = /** @class */ (function () {
        function _StencilState() {
            this._isStencilTestDirty = false;
            this._isStencilMaskDirty = false;
            this._isStencilFuncDirty = false;
            this._isStencilOpDirty = false;
            this.reset();
        }
        Object.defineProperty(_StencilState.prototype, "isDirty", {
            get: function () {
                return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilFunc", {
            get: function () {
                return this._stencilFunc;
            },
            set: function (value) {
                if (this._stencilFunc === value) {
                    return;
                }
                this._stencilFunc = value;
                this._isStencilFuncDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
            get: function () {
                return this._stencilFuncRef;
            },
            set: function (value) {
                if (this._stencilFuncRef === value) {
                    return;
                }
                this._stencilFuncRef = value;
                this._isStencilFuncDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
            get: function () {
                return this._stencilFuncMask;
            },
            set: function (value) {
                if (this._stencilFuncMask === value) {
                    return;
                }
                this._stencilFuncMask = value;
                this._isStencilFuncDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
            get: function () {
                return this._stencilOpStencilFail;
            },
            set: function (value) {
                if (this._stencilOpStencilFail === value) {
                    return;
                }
                this._stencilOpStencilFail = value;
                this._isStencilOpDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
            get: function () {
                return this._stencilOpDepthFail;
            },
            set: function (value) {
                if (this._stencilOpDepthFail === value) {
                    return;
                }
                this._stencilOpDepthFail = value;
                this._isStencilOpDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
            get: function () {
                return this._stencilOpStencilDepthPass;
            },
            set: function (value) {
                if (this._stencilOpStencilDepthPass === value) {
                    return;
                }
                this._stencilOpStencilDepthPass = value;
                this._isStencilOpDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilMask", {
            get: function () {
                return this._stencilMask;
            },
            set: function (value) {
                if (this._stencilMask === value) {
                    return;
                }
                this._stencilMask = value;
                this._isStencilMaskDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(_StencilState.prototype, "stencilTest", {
            get: function () {
                return this._stencilTest;
            },
            set: function (value) {
                if (this._stencilTest === value) {
                    return;
                }
                this._stencilTest = value;
                this._isStencilTestDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        _StencilState.prototype.reset = function () {
            this._stencilTest = false;
            this._stencilMask = 0xFF;
            this._stencilFunc = BABYLON.Engine.ALWAYS;
            this._stencilFuncRef = 1;
            this._stencilFuncMask = 0xFF;
            this._stencilOpStencilFail = BABYLON.Engine.KEEP;
            this._stencilOpDepthFail = BABYLON.Engine.KEEP;
            this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
            this._isStencilTestDirty = true;
            this._isStencilMaskDirty = true;
            this._isStencilFuncDirty = true;
            this._isStencilOpDirty = true;
        };
        _StencilState.prototype.apply = function (gl) {
            if (!this.isDirty) {
                return;
            }
            // Stencil test
            if (this._isStencilTestDirty) {
                if (this.stencilTest) {
                    gl.enable(gl.STENCIL_TEST);
                }
                else {
                    gl.disable(gl.STENCIL_TEST);
                }
                this._isStencilTestDirty = false;
            }
            // Stencil mask
            if (this._isStencilMaskDirty) {
                gl.stencilMask(this.stencilMask);
                this._isStencilMaskDirty = false;
            }
            // Stencil func
            if (this._isStencilFuncDirty) {
                gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
                this._isStencilFuncDirty = false;
            }
            // Stencil op
            if (this._isStencilOpDirty) {
                gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
                this._isStencilOpDirty = false;
            }
        };
        return _StencilState;
    }());
    BABYLON._StencilState = _StencilState;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stencilState.js.map

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var BABYLON;
(function (BABYLON) {
    /**
     * Keeps track of all the buffer info used in engine.
     */
    var BufferPointer = /** @class */ (function () {
        function BufferPointer() {
        }
        return BufferPointer;
    }());
    /**
     * Interface for attribute information associated with buffer instanciation
     */
    var InstancingAttributeInfo = /** @class */ (function () {
        function InstancingAttributeInfo() {
        }
        return InstancingAttributeInfo;
    }());
    BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
    /**
     * Define options used to create a render target texture
     */
    var RenderTargetCreationOptions = /** @class */ (function () {
        function RenderTargetCreationOptions() {
        }
        return RenderTargetCreationOptions;
    }());
    BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
    /**
     * Define options used to create a depth texture
     */
    var DepthTextureCreationOptions = /** @class */ (function () {
        function DepthTextureCreationOptions() {
        }
        return DepthTextureCreationOptions;
    }());
    BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
    /**
     * Class used to describe the capabilities of the engine relatively to the current browser
     */
    var EngineCapabilities = /** @class */ (function () {
        function EngineCapabilities() {
        }
        return EngineCapabilities;
    }());
    BABYLON.EngineCapabilities = EngineCapabilities;
    /**
     * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
     */
    var Engine = /** @class */ (function () {
        /**
         * Creates a new engine
         * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
         * @param antialias defines enable antialiasing (default: false)
         * @param options defines further options to be sent to the getContext() function
         * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
         */
        function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
            if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
            var _this = this;
            // Public members
            /**
             * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
             */
            this.forcePOTTextures = false;
            /**
             * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
             */
            this.isFullscreen = false;
            /**
             * Gets a boolean indicating if the pointer is currently locked
             */
            this.isPointerLock = false;
            /**
             * Gets or sets a boolean indicating if back faces must be culled (true by default)
             */
            this.cullBackFaces = true;
            /**
             * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
             */
            this.renderEvenInBackground = true;
            /**
             * Gets or sets a boolean indicating that cache can be kept between frames
             */
            this.preventCacheWipeBetweenFrames = false;
            /**
             * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
             **/
            this.enableOfflineSupport = false;
            /**
             * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
             **/
            this.disableManifestCheck = false;
            /**
             * Gets the list of created scenes
             */
            this.scenes = new Array();
            /**
             * Gets the list of created postprocesses
             */
            this.postProcesses = new Array();
            /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
            this.validateShaderPrograms = false;
            // Observables
            /**
             * Observable event triggered each time the rendering canvas is resized
             */
            this.onResizeObservable = new BABYLON.Observable();
            /**
             * Observable event triggered each time the canvas loses focus
             */
            this.onCanvasBlurObservable = new BABYLON.Observable();
            /**
             * Observable event triggered each time the canvas gains focus
             */
            this.onCanvasFocusObservable = new BABYLON.Observable();
            /**
             * Observable event triggered each time the canvas receives pointerout event
             */
            this.onCanvasPointerOutObservable = new BABYLON.Observable();
            /**
             * Observable event triggered before each texture is initialized
             */
            this.onBeforeTextureInitObservable = new BABYLON.Observable();
            //WebVR
            this._vrDisplay = undefined;
            this._vrSupported = false;
            this._vrExclusivePointerMode = false;
            // Uniform buffers list
            /**
             * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
             */
            this.disableUniformBuffers = false;
            /** @hidden */
            this._uniformBuffers = new Array();
            // Observables
            /**
             * Observable raised when the engine begins a new frame
             */
            this.onBeginFrameObservable = new BABYLON.Observable();
            /**
             * Observable raised when the engine ends the current frame
             */
            this.onEndFrameObservable = new BABYLON.Observable();
            /**
             * Observable raised when the engine is about to compile a shader
             */
            this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
            /**
             * Observable raised when the engine has jsut compiled a shader
             */
            this.onAfterShaderCompilationObservable = new BABYLON.Observable();
            this._windowIsBackground = false;
            this._webGLVersion = 1.0;
            /** @hidden */
            this._badOS = false;
            /** @hidden */
            this._badDesktopOS = false;
            /**
             * Gets or sets a value indicating if we want to disable texture binding optmization.
             * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
             * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
             */
            this.disableTextureBindingOptimization = false;
            /**
             * Observable signaled when VR display mode changes
             */
            this.onVRDisplayChangedObservable = new BABYLON.Observable();
            /**
             * Observable signaled when VR request present is complete
             */
            this.onVRRequestPresentComplete = new BABYLON.Observable();
            /**
             * Observable signaled when VR request present starts
             */
            this.onVRRequestPresentStart = new BABYLON.Observable();
            this._colorWrite = true;
            /** @hidden */
            this._drawCalls = new BABYLON.PerfCounter();
            /** @hidden */
            this._textureCollisions = new BABYLON.PerfCounter();
            this._renderingQueueLaunched = false;
            this._activeRenderLoops = new Array();
            // Deterministic lockstepMaxSteps
            this._deterministicLockstep = false;
            this._lockstepMaxSteps = 4;
            // Lost context
            /**
             * Observable signaled when a context lost event is raised
             */
            this.onContextLostObservable = new BABYLON.Observable();
            /**
             * Observable signaled when a context restored event is raised
             */
            this.onContextRestoredObservable = new BABYLON.Observable();
            this._contextWasLost = false;
            this._doNotHandleContextLost = false;
            // FPS
            this._performanceMonitor = new BABYLON.PerformanceMonitor();
            this._fps = 60;
            this._deltaTime = 0;
            /**
             * Turn this value on if you want to pause FPS computation when in background
             */
            this.disablePerformanceMonitorInBackground = false;
            // States
            /** @hidden */
            this._depthCullingState = new BABYLON._DepthCullingState();
            /** @hidden */
            this._stencilState = new BABYLON._StencilState();
            /** @hidden */
            this._alphaState = new BABYLON._AlphaState();
            /** @hidden */
            this._alphaMode = Engine.ALPHA_DISABLE;
            // Cache
            this._internalTexturesCache = new Array();
            /** @hidden */
            this._activeChannel = 0;
            this._currentTextureChannel = -1;
            /** @hidden */
            this._boundTexturesCache = {};
            this._compiledEffects = {};
            this._vertexAttribArraysEnabled = [];
            this._uintIndicesCurrentlySet = false;
            this._currentBoundBuffer = new Array();
            /** @hidden */
            this._currentFramebuffer = null;
            this._currentBufferPointers = new Array();
            this._currentInstanceLocations = new Array();
            this._currentInstanceBuffers = new Array();
            this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
            this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
            this._vaoRecordInProgress = false;
            this._mustWipeVertexAttributes = false;
            this._nextFreeTextureSlots = new Array();
            this._maxSimultaneousTextures = 0;
            this._activeRequests = new Array();
            // Hardware supported Compressed Textures
            this._texturesSupported = new Array();
            /**
             * Defines whether the engine has been created with the premultipliedAlpha option on or not.
             */
            this.premultipliedAlpha = true;
            this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
            this._onVRFullScreenTriggered = function () {
                if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
                    //get the old size before we change
                    _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
                    _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
                    //get the width and height, change the render size
                    var leftEye = _this._vrDisplay.getEyeParameters('left');
                    _this.setHardwareScalingLevel(1);
                    _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
                }
                else {
                    _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
                    _this.setSize(_this._oldSize.width, _this._oldSize.height);
                }
            };
            this._unpackFlipYCached = null;
            /**
             * In case you are sharing the context with other applications, it might
             * be interested to not cache the unpack flip y state to ensure a consistent
             * value would be set.
             */
            this.enableUnpackFlipYCached = true;
            this._boundUniforms = {};
            // Register promises
            BABYLON.PromisePolyfill.Apply();
            var canvas = null;
            Engine.Instances.push(this);
            if (!canvasOrContext) {
                return;
            }
            options = options || {};
            if (canvasOrContext.getContext) {
                canvas = canvasOrContext;
                this._renderingCanvas = canvas;
                if (antialias != null) {
                    options.antialias = antialias;
                }
                if (options.deterministicLockstep === undefined) {
                    options.deterministicLockstep = false;
                }
                if (options.lockstepMaxSteps === undefined) {
                    options.lockstepMaxSteps = 4;
                }
                if (options.preserveDrawingBuffer === undefined) {
                    options.preserveDrawingBuffer = false;
                }
                if (options.audioEngine === undefined) {
                    options.audioEngine = true;
                }
                if (options.stencil === undefined) {
                    options.stencil = true;
                }
                if (options.premultipliedAlpha === false) {
                    this.premultipliedAlpha = false;
                }
                this._deterministicLockstep = options.deterministicLockstep;
                this._lockstepMaxSteps = options.lockstepMaxSteps;
                this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
                // Exceptions
                if (navigator && navigator.userAgent) {
                    var ua = navigator.userAgent;
                    for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
                        var exception = _a[_i];
                        var key = exception.key;
                        var targets = exception.targets;
                        if (ua.indexOf(key) > -1) {
                            if (exception.capture && exception.captureConstraint) {
                                var capture = exception.capture;
                                var constraint = exception.captureConstraint;
                                var regex = new RegExp(capture);
                                var matches = regex.exec(ua);
                                if (matches && matches.length > 0) {
                                    var capturedValue = parseInt(matches[matches.length - 1]);
                                    if (capturedValue >= constraint) {
                                        continue;
                                    }
                                }
                            }
                            for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
                                var target = targets_1[_b];
                                switch (target) {
                                    case "uniformBuffer":
                                        this.disableUniformBuffers = true;
                                        break;
                                    case "textureBindingOptimization":
                                        this.disableTextureBindingOptimization = true;
                                        break;
                                }
                            }
                        }
                    }
                }
                // GL
                if (!options.disableWebGL2Support) {
                    try {
                        this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
                        if (this._gl) {
                            this._webGLVersion = 2.0;
                            // Prevent weird browsers to lie :-)
                            if (!this._gl.deleteQuery) {
                                this._webGLVersion = 1.0;
                            }
                        }
                    }
                    catch (e) {
                        // Do nothing
                    }
                }
                if (!this._gl) {
                    if (!canvas) {
                        throw new Error("The provided canvas is null or undefined.");
                    }
                    try {
                        this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
                    }
                    catch (e) {
                        throw new Error("WebGL not supported");
                    }
                }
                if (!this._gl) {
                    throw new Error("WebGL not supported");
                }
                this._onCanvasFocus = function () {
                    _this.onCanvasFocusObservable.notifyObservers(_this);
                };
                this._onCanvasBlur = function () {
                    _this.onCanvasBlurObservable.notifyObservers(_this);
                };
                canvas.addEventListener("focus", this._onCanvasFocus);
                canvas.addEventListener("blur", this._onCanvasBlur);
                this._onBlur = function () {
                    if (_this.disablePerformanceMonitorInBackground) {
                        _this._performanceMonitor.disable();
                    }
                    _this._windowIsBackground = true;
                };
                this._onFocus = function () {
                    if (_this.disablePerformanceMonitorInBackground) {
                        _this._performanceMonitor.enable();
                    }
                    _this._windowIsBackground = false;
                };
                this._onCanvasPointerOut = function (ev) {
                    _this.onCanvasPointerOutObservable.notifyObservers(ev);
                };
                window.addEventListener("blur", this._onBlur);
                window.addEventListener("focus", this._onFocus);
                canvas.addEventListener("pointerout", this._onCanvasPointerOut);
                // Context lost
                if (!this._doNotHandleContextLost) {
                    this._onContextLost = function (evt) {
                        evt.preventDefault();
                        _this._contextWasLost = true;
                        BABYLON.Tools.Warn("WebGL context lost.");
                        _this.onContextLostObservable.notifyObservers(_this);
                    };
                    this._onContextRestored = function (evt) {
                        // Adding a timeout to avoid race condition at browser level
                        setTimeout(function () {
                            // Rebuild gl context
                            _this._initGLContext();
                            // Rebuild effects
                            _this._rebuildEffects();
                            // Rebuild textures
                            _this._rebuildInternalTextures();
                            // Rebuild buffers
                            _this._rebuildBuffers();
                            // Cache
                            _this.wipeCaches(true);
                            BABYLON.Tools.Warn("WebGL context successfully restored.");
                            _this.onContextRestoredObservable.notifyObservers(_this);
                            _this._contextWasLost = false;
                        }, 0);
                    };
                    canvas.addEventListener("webglcontextlost", this._onContextLost, false);
                    canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
                }
            }
            else {
                this._gl = canvasOrContext;
                this._renderingCanvas = this._gl.canvas;
                if (this._gl.renderbufferStorageMultisample) {
                    this._webGLVersion = 2.0;
                }
                var attributes = this._gl.getContextAttributes();
                if (attributes) {
                    options.stencil = attributes.stencil;
                }
            }
            // Viewport
            var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
            this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
            this.resize();
            this._isStencilEnable = options.stencil ? true : false;
            this._initGLContext();
            if (canvas) {
                // Fullscreen
                this._onFullscreenChange = function () {
                    if (document.fullscreen !== undefined) {
                        _this.isFullscreen = document.fullscreen;
                    }
                    else if (document.mozFullScreen !== undefined) {
                        _this.isFullscreen = document.mozFullScreen;
                    }
                    else if (document.webkitIsFullScreen !== undefined) {
                        _this.isFullscreen = document.webkitIsFullScreen;
                    }
                    else if (document.msIsFullScreen !== undefined) {
                        _this.isFullscreen = document.msIsFullScreen;
                    }
                    // Pointer lock
                    if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
                        canvas.requestPointerLock = canvas.requestPointerLock ||
                            canvas.msRequestPointerLock ||
                            canvas.mozRequestPointerLock ||
                            canvas.webkitRequestPointerLock;
                        if (canvas.requestPointerLock) {
                            canvas.requestPointerLock();
                        }
                    }
                };
                document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
                document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
                document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
                document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
                // Pointer lock
                this._onPointerLockChange = function () {
                    _this.isPointerLock = (document.mozPointerLockElement === canvas ||
                        document.webkitPointerLockElement === canvas ||
                        document.msPointerLockElement === canvas ||
                        document.pointerLockElement === canvas);
                };
                document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
                document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
                document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
                document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
                this._onVRDisplayPointerRestricted = function () {
                    if (canvas) {
                        canvas.requestPointerLock();
                    }
                };
                this._onVRDisplayPointerUnrestricted = function () {
                    document.exitPointerLock();
                };
                window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
                window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
            }
            // Create Audio Engine if needed.
            if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
                Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
            }
            // Prepare buffer pointers
            for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
                this._currentBufferPointers[i] = new BufferPointer();
            }
            this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
            // Load WebVR Devices
            if (options.autoEnableWebVR) {
                this.initWebVR();
            }
            // Detect if we are running on a faulty buggy OS.
            this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
            // Detect if we are running on a faulty buggy desktop OS.
            this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
            console.log("Babylon.js engine (v" + Engine.Version + ") launched");
            this.enableOfflineSupport = (BABYLON.Database !== undefined);
        }
        Object.defineProperty(Engine, "LastCreatedEngine", {
            /**
             * Gets the latest created engine
             */
            get: function () {
                if (Engine.Instances.length === 0) {
                    return null;
                }
                return Engine.Instances[Engine.Instances.length - 1];
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine, "LastCreatedScene", {
            /**
             * Gets the latest created scene
             */
            get: function () {
                var lastCreatedEngine = Engine.LastCreatedEngine;
                if (!lastCreatedEngine) {
                    return null;
                }
                if (lastCreatedEngine.scenes.length === 0) {
                    return null;
                }
                return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
         * @param flag defines which part of the materials must be marked as dirty
         * @param predicate defines a predicate used to filter which materials should be affected
         */
        Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
            for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
                var engine = Engine.Instances[engineIndex];
                for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
                    engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
                }
            }
        };
        Object.defineProperty(Engine, "Version", {
            /**
             * Returns the current version of the framework
             */
            get: function () {
                return "3.3.0";
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
            /**
             * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
             * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
             */
            get: function () {
                return this._vrExclusivePointerMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
            /**
             * Gets a boolean indicating that the engine supports uniform buffers
             * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
             */
            get: function () {
                return this.webGLVersion > 1 && !this.disableUniformBuffers;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "needPOTTextures", {
            /**
             * Gets a boolean indicating that only power of 2 textures are supported
             * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
             */
            get: function () {
                return this._webGLVersion < 2 || this.forcePOTTextures;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
            /**
             * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
             * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
             */
            get: function () {
                return this._doNotHandleContextLost;
            },
            set: function (value) {
                this._doNotHandleContextLost = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "performanceMonitor", {
            /**
             * Gets the performance monitor attached to this engine
             * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
             */
            get: function () {
                return this._performanceMonitor;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "texturesSupported", {
            /**
             * Gets the list of texture formats supported
             */
            get: function () {
                return this._texturesSupported;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "textureFormatInUse", {
            /**
             * Gets the list of texture formats in use
             */
            get: function () {
                return this._textureFormatInUse;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "currentViewport", {
            /**
             * Gets the current viewport
             */
            get: function () {
                return this._cachedViewport;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "emptyTexture", {
            /**
             * Gets the default empty texture
             */
            get: function () {
                if (!this._emptyTexture) {
                    this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
                }
                return this._emptyTexture;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "emptyTexture3D", {
            /**
             * Gets the default empty 3D texture
             */
            get: function () {
                if (!this._emptyTexture3D) {
                    this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
                }
                return this._emptyTexture3D;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
            /**
             * Gets the default empty cube texture
             */
            get: function () {
                if (!this._emptyCubeTexture) {
                    var faceData = new Uint8Array(4);
                    var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
                    this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
                }
                return this._emptyCubeTexture;
            },
            enumerable: true,
            configurable: true
        });
        Engine.prototype._rebuildInternalTextures = function () {
            var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
            for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
                var internalTexture = currentState_1[_i];
                internalTexture._rebuild();
            }
        };
        Engine.prototype._rebuildEffects = function () {
            for (var key in this._compiledEffects) {
                var effect = this._compiledEffects[key];
                effect._prepareEffect();
            }
            BABYLON.Effect.ResetCache();
        };
        Engine.prototype._rebuildBuffers = function () {
            // Index / Vertex
            for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
                var scene = _a[_i];
                scene.resetCachedMaterial();
                scene._rebuildGeometries();
                scene._rebuildTextures();
            }
            // Uniforms
            for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
                var uniformBuffer = _c[_b];
                uniformBuffer._rebuild();
            }
        };
        Engine.prototype._initGLContext = function () {
            // Caps
            this._caps = new EngineCapabilities();
            this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
            this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
            this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
            this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
            this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
            this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
            this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
            this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
            this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
            this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
            // Infos
            this._glVersion = this._gl.getParameter(this._gl.VERSION);
            var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
            if (rendererInfo != null) {
                this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
                this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
            }
            if (!this._glVendor) {
                this._glVendor = "Unknown vendor";
            }
            if (!this._glRenderer) {
                this._glRenderer = "Unknown renderer";
            }
            // Constants
            this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
            if (this._gl.RGBA16F !== 0x881A) {
                this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
            }
            if (this._gl.RGBA32F !== 0x8814) {
                this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
            }
            if (this._gl.DEPTH24_STENCIL8 !== 35056) {
                this._gl.DEPTH24_STENCIL8 = 35056;
            }
            // Extensions
            this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
            this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
            this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
            this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
            this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
            this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
                this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
            this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
            this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
            this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
            this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
            this._caps.highPrecisionShaderSupported = true;
            this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
            if (this._caps.timerQuery) {
                if (this._webGLVersion === 1) {
                    this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
                }
                this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
            }
            // Checks if some of the format renders first to allow the use of webgl inspector.
            this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
            this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
            this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
            this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
            this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
            this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
            if (this._webGLVersion > 1) {
                this._gl.HALF_FLOAT_OES = 0x140B;
            }
            this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
            this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
            // Draw buffers
            if (this._webGLVersion > 1) {
                this._caps.drawBuffersExtension = true;
            }
            else {
                var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
                if (drawBuffersExtension !== null) {
                    this._caps.drawBuffersExtension = true;
                    this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
                    this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
                    for (var i = 0; i < 16; i++) {
                        this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
                    }
                }
                else {
                    this._caps.drawBuffersExtension = false;
                }
            }
            // Depth Texture
            if (this._webGLVersion > 1) {
                this._caps.depthTextureExtension = true;
            }
            else {
                var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
                if (depthTextureExtension != null) {
                    this._caps.depthTextureExtension = true;
                    this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
                }
            }
            // Vertex array object
            if (this._webGLVersion > 1) {
                this._caps.vertexArrayObject = true;
            }
            else {
                var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
                if (vertexArrayObjectExtension != null) {
                    this._caps.vertexArrayObject = true;
                    this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
                    this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
                    this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
                }
                else {
                    this._caps.vertexArrayObject = false;
                }
            }
            // Instances count
            if (this._webGLVersion > 1) {
                this._caps.instancedArrays = true;
            }
            else {
                var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
                if (instanceExtension != null) {
                    this._caps.instancedArrays = true;
                    this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
                    this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
                    this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
                }
                else {
                    this._caps.instancedArrays = false;
                }
            }
            // Intelligently add supported compressed formats in order to check for.
            // Check for ASTC support first as it is most powerful and to be very cross platform.
            // Next PVRTC & DXT, which are probably superior to ETC1/2.
            // Likely no hardware which supports both PVR & DXT, so order matters little.
            // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
            if (this._caps.astc) {
                this.texturesSupported.push('-astc.ktx');
            }
            if (this._caps.s3tc) {
                this.texturesSupported.push('-dxt.ktx');
            }
            if (this._caps.pvrtc) {
                this.texturesSupported.push('-pvrtc.ktx');
            }
            if (this._caps.etc2) {
                this.texturesSupported.push('-etc2.ktx');
            }
            if (this._caps.etc1) {
                this.texturesSupported.push('-etc1.ktx');
            }
            if (this._gl.getShaderPrecisionFormat) {
                var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
                if (highp) {
                    this._caps.highPrecisionShaderSupported = highp.precision !== 0;
                }
            }
            // Depth buffer
            this.setDepthBuffer(true);
            this.setDepthFunctionToLessOrEqual();
            this.setDepthWrite(true);
            // Texture maps
            this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
            for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
                this._nextFreeTextureSlots.push(slot);
            }
        };
        Object.defineProperty(Engine.prototype, "webGLVersion", {
            /**
             * Gets version of the current webGL context
             */
            get: function () {
                return this._webGLVersion;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "isStencilEnable", {
            /**
             * Returns true if the stencil buffer has been enabled through the creation option of the context.
             */
            get: function () {
                return this._isStencilEnable;
            },
            enumerable: true,
            configurable: true
        });
        Engine.prototype._prepareWorkingCanvas = function () {
            if (this._workingCanvas) {
                return;
            }
            this._workingCanvas = document.createElement("canvas");
            var context = this._workingCanvas.getContext("2d");
            if (context) {
                this._workingContext = context;
            }
        };
        /**
         * Reset the texture cache to empty state
         */
        Engine.prototype.resetTextureCache = function () {
            for (var key in this._boundTexturesCache) {
                if (!this._boundTexturesCache.hasOwnProperty(key)) {
                    continue;
                }
                var boundTexture = this._boundTexturesCache[key];
                if (boundTexture) {
                    this._removeDesignatedSlot(boundTexture);
                }
                this._boundTexturesCache[key] = null;
            }
            if (!this.disableTextureBindingOptimization) {
                this._nextFreeTextureSlots = [];
                for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
                    this._nextFreeTextureSlots.push(slot);
                }
            }
            this._currentTextureChannel = -1;
        };
        /**
         * Gets a boolean indicating that the engine is running in deterministic lock step mode
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         * @returns true if engine is in deterministic lock step mode
         */
        Engine.prototype.isDeterministicLockStep = function () {
            return this._deterministicLockstep;
        };
        /**
         * Gets the max steps when engine is running in deterministic lock step
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         * @returns the max steps
         */
        Engine.prototype.getLockstepMaxSteps = function () {
            return this._lockstepMaxSteps;
        };
        /**
         * Gets an object containing information about the current webGL context
         * @returns an object containing the vender, the renderer and the version of the current webGL context
         */
        Engine.prototype.getGlInfo = function () {
            return {
                vendor: this._glVendor,
                renderer: this._glRenderer,
                version: this._glVersion
            };
        };
        /**
         * Gets current aspect ratio
         * @param camera defines the camera to use to get the aspect ratio
         * @param useScreen defines if screen size must be used (or the current render target if any)
         * @returns a number defining the aspect ratio
         */
        Engine.prototype.getAspectRatio = function (camera, useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            var viewport = camera.viewport;
            return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
        };
        /**
         * Gets current screen aspect ratio
         * @returns a number defining the aspect ratio
         */
        Engine.prototype.getScreenAspectRatio = function () {
            return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
        };
        /**
         * Gets the current render width
         * @param useScreen defines if screen size must be used (or the current render target if any)
         * @returns a number defining the current render width
         */
        Engine.prototype.getRenderWidth = function (useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            if (!useScreen && this._currentRenderTarget) {
                return this._currentRenderTarget.width;
            }
            return this._gl.drawingBufferWidth;
        };
        /**
         * Gets the current render height
         * @param useScreen defines if screen size must be used (or the current render target if any)
         * @returns a number defining the current render height
         */
        Engine.prototype.getRenderHeight = function (useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            if (!useScreen && this._currentRenderTarget) {
                return this._currentRenderTarget.height;
            }
            return this._gl.drawingBufferHeight;
        };
        /**
         * Gets the HTML canvas attached with the current webGL context
         * @returns a HTML canvas
         */
        Engine.prototype.getRenderingCanvas = function () {
            return this._renderingCanvas;
        };
        /**
         * Gets the client rect of the HTML canvas attached with the current webGL context
         * @returns a client rectanglee
         */
        Engine.prototype.getRenderingCanvasClientRect = function () {
            if (!this._renderingCanvas) {
                return null;
            }
            return this._renderingCanvas.getBoundingClientRect();
        };
        /**
         * Defines the hardware scaling level.
         * By default the hardware scaling level is computed from the window device ratio.
         * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
         * @param level defines the level to use
         */
        Engine.prototype.setHardwareScalingLevel = function (level) {
            this._hardwareScalingLevel = level;
            this.resize();
        };
        /**
         * Gets the current hardware scaling level.
         * By default the hardware scaling level is computed from the window device ratio.
         * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
         * @returns a number indicating the current hardware scaling level
         */
        Engine.prototype.getHardwareScalingLevel = function () {
            return this._hardwareScalingLevel;
        };
        /**
         * Gets the list of loaded textures
         * @returns an array containing all loaded textures
         */
        Engine.prototype.getLoadedTexturesCache = function () {
            return this._internalTexturesCache;
        };
        /**
         * Gets the object containing all engine capabilities
         * @returns the EngineCapabilities object
         */
        Engine.prototype.getCaps = function () {
            return this._caps;
        };
        Object.defineProperty(Engine.prototype, "drawCalls", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
                return 0;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the current depth function
         * @returns a number defining the depth function
         */
        Engine.prototype.getDepthFunction = function () {
            return this._depthCullingState.depthFunc;
        };
        /**
         * Sets the current depth function
         * @param depthFunc defines the function to use
         */
        Engine.prototype.setDepthFunction = function (depthFunc) {
            this._depthCullingState.depthFunc = depthFunc;
        };
        /**
         * Sets the current depth function to GREATER
         */
        Engine.prototype.setDepthFunctionToGreater = function () {
            this._depthCullingState.depthFunc = this._gl.GREATER;
        };
        /**
         * Sets the current depth function to GEQUAL
         */
        Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
            this._depthCullingState.depthFunc = this._gl.GEQUAL;
        };
        /**
         * Sets the current depth function to LESS
         */
        Engine.prototype.setDepthFunctionToLess = function () {
            this._depthCullingState.depthFunc = this._gl.LESS;
        };
        /**
         * Sets the current depth function to LEQUAL
         */
        Engine.prototype.setDepthFunctionToLessOrEqual = function () {
            this._depthCullingState.depthFunc = this._gl.LEQUAL;
        };
        /**
         * Gets a boolean indicating if stencil buffer is enabled
         * @returns the current stencil buffer state
         */
        Engine.prototype.getStencilBuffer = function () {
            return this._stencilState.stencilTest;
        };
        /**
         * Enable or disable the stencil buffer
         * @param enable defines if the stencil buffer must be enabled or disabled
         */
        Engine.prototype.setStencilBuffer = function (enable) {
            this._stencilState.stencilTest = enable;
        };
        /**
         * Gets the current stencil mask
         * @returns a number defining the new stencil mask to use
         */
        Engine.prototype.getStencilMask = function () {
            return this._stencilState.stencilMask;
        };
        /**
         * Sets the current stencil mask
         * @param mask defines the new stencil mask to use
         */
        Engine.prototype.setStencilMask = function (mask) {
            this._stencilState.stencilMask = mask;
        };
        /**
         * Gets the current stencil function
         * @returns a number defining the stencil function to use
         */
        Engine.prototype.getStencilFunction = function () {
            return this._stencilState.stencilFunc;
        };
        /**
         * Gets the current stencil reference value
         * @returns a number defining the stencil reference value to use
         */
        Engine.prototype.getStencilFunctionReference = function () {
            return this._stencilState.stencilFuncRef;
        };
        /**
         * Gets the current stencil mask
         * @returns a number defining the stencil mask to use
         */
        Engine.prototype.getStencilFunctionMask = function () {
            return this._stencilState.stencilFuncMask;
        };
        /**
         * Sets the current stencil function
         * @param stencilFunc defines the new stencil function to use
         */
        Engine.prototype.setStencilFunction = function (stencilFunc) {
            this._stencilState.stencilFunc = stencilFunc;
        };
        /**
         * Sets the current stencil reference
         * @param reference defines the new stencil reference to use
         */
        Engine.prototype.setStencilFunctionReference = function (reference) {
            this._stencilState.stencilFuncRef = reference;
        };
        /**
         * Sets the current stencil mask
         * @param mask defines the new stencil mask to use
         */
        Engine.prototype.setStencilFunctionMask = function (mask) {
            this._stencilState.stencilFuncMask = mask;
        };
        /**
         * Gets the current stencil operation when stencil fails
         * @returns a number defining stencil operation to use when stencil fails
         */
        Engine.prototype.getStencilOperationFail = function () {
            return this._stencilState.stencilOpStencilFail;
        };
        /**
         * Gets the current stencil operation when depth fails
         * @returns a number defining stencil operation to use when depth fails
         */
        Engine.prototype.getStencilOperationDepthFail = function () {
            return this._stencilState.stencilOpDepthFail;
        };
        /**
         * Gets the current stencil operation when stencil passes
         * @returns a number defining stencil operation to use when stencil passes
         */
        Engine.prototype.getStencilOperationPass = function () {
            return this._stencilState.stencilOpStencilDepthPass;
        };
        /**
         * Sets the stencil operation to use when stencil fails
         * @param operation defines the stencil operation to use when stencil fails
         */
        Engine.prototype.setStencilOperationFail = function (operation) {
            this._stencilState.stencilOpStencilFail = operation;
        };
        /**
         * Sets the stencil operation to use when depth fails
         * @param operation defines the stencil operation to use when depth fails
         */
        Engine.prototype.setStencilOperationDepthFail = function (operation) {
            this._stencilState.stencilOpDepthFail = operation;
        };
        /**
         * Sets the stencil operation to use when stencil passes
         * @param operation defines the stencil operation to use when stencil passes
         */
        Engine.prototype.setStencilOperationPass = function (operation) {
            this._stencilState.stencilOpStencilDepthPass = operation;
        };
        /**
         * Sets a boolean indicating if the dithering state is enabled or disabled
         * @param value defines the dithering state
         */
        Engine.prototype.setDitheringState = function (value) {
            if (value) {
                this._gl.enable(this._gl.DITHER);
            }
            else {
                this._gl.disable(this._gl.DITHER);
            }
        };
        /**
         * Sets a boolean indicating if the rasterizer state is enabled or disabled
         * @param value defines the rasterizer state
         */
        Engine.prototype.setRasterizerState = function (value) {
            if (value) {
                this._gl.disable(this._gl.RASTERIZER_DISCARD);
            }
            else {
                this._gl.enable(this._gl.RASTERIZER_DISCARD);
            }
        };
        /**
         * stop executing a render loop function and remove it from the execution array
         * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
         */
        Engine.prototype.stopRenderLoop = function (renderFunction) {
            if (!renderFunction) {
                this._activeRenderLoops = [];
                return;
            }
            var index = this._activeRenderLoops.indexOf(renderFunction);
            if (index >= 0) {
                this._activeRenderLoops.splice(index, 1);
            }
        };
        /** @hidden */
        Engine.prototype._renderLoop = function () {
            if (!this._contextWasLost) {
                var shouldRender = true;
                if (!this.renderEvenInBackground && this._windowIsBackground) {
                    shouldRender = false;
                }
                if (shouldRender) {
                    // Start new frame
                    this.beginFrame();
                    for (var index = 0; index < this._activeRenderLoops.length; index++) {
                        var renderFunction = this._activeRenderLoops[index];
                        renderFunction();
                    }
                    // Present
                    this.endFrame();
                }
            }
            if (this._activeRenderLoops.length > 0) {
                // Register new frame
                var requester = null;
                if (this._vrDisplay && this._vrDisplay.isPresenting) {
                    requester = this._vrDisplay;
                }
                this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
            }
            else {
                this._renderingQueueLaunched = false;
            }
        };
        /**
         * Register and execute a render loop. The engine can have more than one render function
         * @param renderFunction defines the function to continuously execute
         */
        Engine.prototype.runRenderLoop = function (renderFunction) {
            if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
                return;
            }
            this._activeRenderLoops.push(renderFunction);
            if (!this._renderingQueueLaunched) {
                this._renderingQueueLaunched = true;
                this._bindedRenderFunction = this._renderLoop.bind(this);
                this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
            }
        };
        /**
         * Toggle full screen mode
         * @param requestPointerLock defines if a pointer lock should be requested from the user
         */
        Engine.prototype.switchFullscreen = function (requestPointerLock) {
            if (this.isFullscreen) {
                BABYLON.Tools.ExitFullscreen();
            }
            else {
                this._pointerLockRequested = requestPointerLock;
                if (this._renderingCanvas) {
                    BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
                }
            }
        };
        /**
         * Clear the current render buffer or the current render target (if any is set up)
         * @param color defines the color to use
         * @param backBuffer defines if the back buffer must be cleared
         * @param depth defines if the depth buffer must be cleared
         * @param stencil defines if the stencil buffer must be cleared
         */
        Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
            if (stencil === void 0) { stencil = false; }
            this.applyStates();
            var mode = 0;
            if (backBuffer && color) {
                this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
                mode |= this._gl.COLOR_BUFFER_BIT;
            }
            if (depth) {
                this._gl.clearDepth(1.0);
                mode |= this._gl.DEPTH_BUFFER_BIT;
            }
            if (stencil) {
                this._gl.clearStencil(0);
                mode |= this._gl.STENCIL_BUFFER_BIT;
            }
            this._gl.clear(mode);
        };
        /**
         * Executes a scissor clear (ie. a clear on a specific portion of the screen)
         * @param x defines the x-coordinate of the top left corner of the clear rectangle
         * @param y defines the y-coordinate of the corner of the clear rectangle
         * @param width defines the width of the clear rectangle
         * @param height defines the height of the clear rectangle
         * @param clearColor defines the clear color
         */
        Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
            var gl = this._gl;
            // Save state
            var curScissor = gl.getParameter(gl.SCISSOR_TEST);
            var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
            // Change state
            gl.enable(gl.SCISSOR_TEST);
            gl.scissor(x, y, width, height);
            // Clear
            this.clear(clearColor, true, true, true);
            // Restore state
            gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
            if (curScissor === true) {
                gl.enable(gl.SCISSOR_TEST);
            }
            else {
                gl.disable(gl.SCISSOR_TEST);
            }
        };
        /** @hidden */
        Engine.prototype._viewport = function (x, y, width, height) {
            if (x !== this._viewportCached.x ||
                y !== this._viewportCached.y ||
                width !== this._viewportCached.z ||
                height !== this._viewportCached.w) {
                this._viewportCached.x = x;
                this._viewportCached.y = y;
                this._viewportCached.z = width;
                this._viewportCached.w = height;
                this._gl.viewport(x, y, width, height);
            }
        };
        /**
         * Set the WebGL's viewport
         * @param viewport defines the viewport element to be used
         * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
         * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
         */
        Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
            var width = requiredWidth || this.getRenderWidth();
            var height = requiredHeight || this.getRenderHeight();
            var x = viewport.x || 0;
            var y = viewport.y || 0;
            this._cachedViewport = viewport;
            this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
        };
        /**
         * Directly set the WebGL Viewport
         * @param x defines the x coordinate of the viewport (in screen space)
         * @param y defines the y coordinate of the viewport (in screen space)
         * @param width defines the width of the viewport (in screen space)
         * @param height defines the height of the viewport (in screen space)
         * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
         */
        Engine.prototype.setDirectViewport = function (x, y, width, height) {
            var currentViewport = this._cachedViewport;
            this._cachedViewport = null;
            this._viewport(x, y, width, height);
            return currentViewport;
        };
        /**
         * Begin a new frame
         */
        Engine.prototype.beginFrame = function () {
            this.onBeginFrameObservable.notifyObservers(this);
            this._measureFps();
        };
        /**
         * Enf the current frame
         */
        Engine.prototype.endFrame = function () {
            // Force a flush in case we are using a bad OS.
            if (this._badOS) {
                this.flushFramebuffer();
            }
            // Submit frame to the vr device, if enabled
            if (this._vrDisplay && this._vrDisplay.isPresenting) {
                // TODO: We should only submit the frame if we read frameData successfully.
                this._vrDisplay.submitFrame();
            }
            this.onEndFrameObservable.notifyObservers(this);
        };
        /**
         * Resize the view according to the canvas' size
         */
        Engine.prototype.resize = function () {
            // We're not resizing the size of the canvas while in VR mode & presenting
            if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
                var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
                var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
                this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
            }
        };
        /**
         * Force a specific size of the canvas
         * @param width defines the new canvas' width
         * @param height defines the new canvas' height
         */
        Engine.prototype.setSize = function (width, height) {
            if (!this._renderingCanvas) {
                return;
            }
            if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
                return;
            }
            this._renderingCanvas.width = width;
            this._renderingCanvas.height = height;
            for (var index = 0; index < this.scenes.length; index++) {
                var scene = this.scenes[index];
                for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
                    var cam = scene.cameras[camIndex];
                    cam._currentRenderId = 0;
                }
            }
            if (this.onResizeObservable.hasObservers) {
                this.onResizeObservable.notifyObservers(this);
            }
        };
        // WebVR functions
        /**
         * Gets a boolean indicating if a webVR device was detected
         * @returns true if a webVR device was detected
         */
        Engine.prototype.isVRDevicePresent = function () {
            return !!this._vrDisplay;
        };
        /**
         * Gets the current webVR device
         * @returns the current webVR device (or null)
         */
        Engine.prototype.getVRDevice = function () {
            return this._vrDisplay;
        };
        /**
         * Initializes a webVR display and starts listening to display change events
         * The onVRDisplayChangedObservable will be notified upon these changes
         * @returns The onVRDisplayChangedObservable
         */
        Engine.prototype.initWebVR = function () {
            this.initWebVRAsync();
            return this.onVRDisplayChangedObservable;
        };
        /**
         * Initializes a webVR display and starts listening to display change events
         * The onVRDisplayChangedObservable will be notified upon these changes
         * @returns A promise containing a VRDisplay and if vr is supported
         */
        Engine.prototype.initWebVRAsync = function () {
            var _this = this;
            var notifyObservers = function () {
                var eventArgs = {
                    vrDisplay: _this._vrDisplay,
                    vrSupported: _this._vrSupported
                };
                _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
                _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
            };
            if (!this._onVrDisplayConnect) {
                this._onVrDisplayConnect = function (event) {
                    _this._vrDisplay = event.display;
                    notifyObservers();
                };
                this._onVrDisplayDisconnect = function () {
                    _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
                    _this._vrDisplay = undefined;
                    _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
                    notifyObservers();
                };
                this._onVrDisplayPresentChange = function () {
                    _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
                };
                window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
                window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
                window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
            }
            this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
            this._webVRInitPromise.then(notifyObservers);
            return this._webVRInitPromise;
        };
        /**
         * Call this function to switch to webVR mode
         * Will do nothing if webVR is not supported or if there is no webVR device
         * @see http://doc.babylonjs.com/how_to/webvr_camera
         */
        Engine.prototype.enableVR = function () {
            var _this = this;
            if (this._vrDisplay && !this._vrDisplay.isPresenting) {
                var onResolved = function () {
                    _this.onVRRequestPresentComplete.notifyObservers(true);
                    _this._onVRFullScreenTriggered();
                };
                var onRejected = function () {
                    _this.onVRRequestPresentComplete.notifyObservers(false);
                };
                this.onVRRequestPresentStart.notifyObservers(this);
                this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
            }
        };
        /**
         * Call this function to leave webVR mode
         * Will do nothing if webVR is not supported or if there is no webVR device
         * @see http://doc.babylonjs.com/how_to/webvr_camera
         */
        Engine.prototype.disableVR = function () {
            if (this._vrDisplay && this._vrDisplay.isPresenting) {
                this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
            }
        };
        Engine.prototype._getVRDisplaysAsync = function () {
            var _this = this;
            return new Promise(function (res, rej) {
                if (navigator.getVRDisplays) {
                    navigator.getVRDisplays().then(function (devices) {
                        _this._vrSupported = true;
                        // note that devices may actually be an empty array. This is fine;
                        // we expect this._vrDisplay to be undefined in this case.
                        _this._vrDisplay = devices[0];
                        res({
                            vrDisplay: _this._vrDisplay,
                            vrSupported: _this._vrSupported
                        });
                    });
                }
                else {
                    _this._vrDisplay = undefined;
                    _this._vrSupported = false;
                    res({
                        vrDisplay: _this._vrDisplay,
                        vrSupported: _this._vrSupported
                    });
                }
            });
        };
        /**
         * Binds the frame buffer to the specified texture.
         * @param texture The texture to render to or null for the default canvas
         * @param faceIndex The face of the texture to render to in case of cube texture
         * @param requiredWidth The width of the target to render to
         * @param requiredHeight The height of the target to render to
         * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
         * @param depthStencilTexture The depth stencil texture to use to render
         * @param lodLevel defines le lod level to bind to the frame buffer
         */
        Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
            if (lodLevel === void 0) { lodLevel = 0; }
            if (this._currentRenderTarget) {
                this.unBindFramebuffer(this._currentRenderTarget);
            }
            this._currentRenderTarget = texture;
            this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
            var gl = this._gl;
            if (texture.isCube) {
                if (faceIndex === undefined) {
                    faceIndex = 0;
                }
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
                if (depthStencilTexture) {
                    if (depthStencilTexture._generateStencilBuffer) {
                        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
                    }
                    else {
                        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
                    }
                }
            }
            if (this._cachedViewport && !forceFullscreenViewport) {
                this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
            }
            else {
                if (!requiredWidth) {
                    requiredWidth = texture.width;
                    if (lodLevel) {
                        requiredWidth = requiredWidth / Math.pow(2, lodLevel);
                    }
                }
                if (!requiredHeight) {
                    requiredHeight = texture.height;
                    if (lodLevel) {
                        requiredHeight = requiredHeight / Math.pow(2, lodLevel);
                    }
                }
                this._viewport(0, 0, requiredWidth, requiredHeight);
            }
            this.wipeCaches();
        };
        Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
            if (this._currentFramebuffer !== framebuffer) {
                this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
                this._currentFramebuffer = framebuffer;
            }
        };
        /**
         * Unbind the current render target texture from the webGL context
         * @param texture defines the render target texture to unbind
         * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
         * @param onBeforeUnbind defines a function which will be called before the effective unbind
         */
        Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
            if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
            this._currentRenderTarget = null;
            // If MSAA, we need to bitblt back to main texture
            var gl = this._gl;
            if (texture._MSAAFramebuffer) {
                gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
                gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
                gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
            }
            if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
                this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
                gl.generateMipmap(gl.TEXTURE_2D);
                this._bindTextureDirectly(gl.TEXTURE_2D, null);
            }
            if (onBeforeUnbind) {
                if (texture._MSAAFramebuffer) {
                    // Bind the correct framebuffer
                    this.bindUnboundFramebuffer(texture._framebuffer);
                }
                onBeforeUnbind();
            }
            this.bindUnboundFramebuffer(null);
        };
        /**
         * Unbind a list of render target textures from the webGL context
         * This is used only when drawBuffer extension or webGL2 are active
         * @param textures defines the render target textures to unbind
         * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
         * @param onBeforeUnbind defines a function which will be called before the effective unbind
         */
        Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
            if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
            this._currentRenderTarget = null;
            // If MSAA, we need to bitblt back to main texture
            var gl = this._gl;
            if (textures[0]._MSAAFramebuffer) {
                gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
                gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
                var attachments = textures[0]._attachments;
                if (!attachments) {
                    attachments = new Array(textures.length);
                    textures[0]._attachments = attachments;
                }
                for (var i = 0; i < textures.length; i++) {
                    var texture = textures[i];
                    for (var j = 0; j < attachments.length; j++) {
                        attachments[j] = gl.NONE;
                    }
                    attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
                    gl.readBuffer(attachments[i]);
                    gl.drawBuffers(attachments);
                    gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
                }
                for (var i = 0; i < attachments.length; i++) {
                    attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
                }
                gl.drawBuffers(attachments);
            }
            for (var i = 0; i < textures.length; i++) {
                var texture = textures[i];
                if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
                    this._bindTextureDirectly(gl.TEXTURE_2D, texture);
                    gl.generateMipmap(gl.TEXTURE_2D);
                    this._bindTextureDirectly(gl.TEXTURE_2D, null);
                }
            }
            if (onBeforeUnbind) {
                if (textures[0]._MSAAFramebuffer) {
                    // Bind the correct framebuffer
                    this.bindUnboundFramebuffer(textures[0]._framebuffer);
                }
                onBeforeUnbind();
            }
            this.bindUnboundFramebuffer(null);
        };
        /**
         * Force the mipmap generation for the given render target texture
         * @param texture defines the render target texture to use
         */
        Engine.prototype.generateMipMapsForCubemap = function (texture) {
            if (texture.generateMipMaps) {
                var gl = this._gl;
                this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
                gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            }
        };
        /**
         * Force a webGL flush (ie. a flush of all waiting webGL commands)
         */
        Engine.prototype.flushFramebuffer = function () {
            this._gl.flush();
        };
        /**
         * Unbind the current render target and bind the default framebuffer
         */
        Engine.prototype.restoreDefaultFramebuffer = function () {
            if (this._currentRenderTarget) {
                this.unBindFramebuffer(this._currentRenderTarget);
            }
            else {
                this.bindUnboundFramebuffer(null);
            }
            if (this._cachedViewport) {
                this.setViewport(this._cachedViewport);
            }
            this.wipeCaches();
        };
        // UBOs
        /**
         * Create an uniform buffer
         * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
         * @param elements defines the content of the uniform buffer
         * @returns the webGL uniform buffer
         */
        Engine.prototype.createUniformBuffer = function (elements) {
            var ubo = this._gl.createBuffer();
            if (!ubo) {
                throw new Error("Unable to create uniform buffer");
            }
            this.bindUniformBuffer(ubo);
            if (elements instanceof Float32Array) {
                this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
            }
            else {
                this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
            }
            this.bindUniformBuffer(null);
            ubo.references = 1;
            return ubo;
        };
        /**
         * Create a dynamic uniform buffer
         * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
         * @param elements defines the content of the uniform buffer
         * @returns the webGL uniform buffer
         */
        Engine.prototype.createDynamicUniformBuffer = function (elements) {
            var ubo = this._gl.createBuffer();
            if (!ubo) {
                throw new Error("Unable to create dynamic uniform buffer");
            }
            this.bindUniformBuffer(ubo);
            if (elements instanceof Float32Array) {
                this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
            }
            else {
                this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
            }
            this.bindUniformBuffer(null);
            ubo.references = 1;
            return ubo;
        };
        /**
         * Update an existing uniform buffer
         * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
         * @param uniformBuffer defines the target uniform buffer
         * @param elements defines the content to update
         * @param offset defines the offset in the uniform buffer where update should start
         * @param count defines the size of the data to update
         */
        Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
            this.bindUniformBuffer(uniformBuffer);
            if (offset === undefined) {
                offset = 0;
            }
            if (count === undefined) {
                if (elements instanceof Float32Array) {
                    this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
                }
                else {
                    this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
                }
            }
            else {
                if (elements instanceof Float32Array) {
                    this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
                }
                else {
                    this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
                }
            }
            this.bindUniformBuffer(null);
        };
        // VBOs
        Engine.prototype._resetVertexBufferBinding = function () {
            this.bindArrayBuffer(null);
            this._cachedVertexBuffers = null;
        };
        /**
         * Creates a vertex buffer
         * @param data the data for the vertex buffer
         * @returns the new WebGL static buffer
         */
        Engine.prototype.createVertexBuffer = function (data) {
            var vbo = this._gl.createBuffer();
            if (!vbo) {
                throw new Error("Unable to create vertex buffer");
            }
            this.bindArrayBuffer(vbo);
            if (data instanceof Array) {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
            }
            else {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
            }
            this._resetVertexBufferBinding();
            vbo.references = 1;
            return vbo;
        };
        /**
         * Creates a dynamic vertex buffer
         * @param data the data for the dynamic vertex buffer
         * @returns the new WebGL dynamic buffer
         */
        Engine.prototype.createDynamicVertexBuffer = function (data) {
            var vbo = this._gl.createBuffer();
            if (!vbo) {
                throw new Error("Unable to create dynamic vertex buffer");
            }
            this.bindArrayBuffer(vbo);
            if (data instanceof Array) {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
            }
            else {
                this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
            }
            this._resetVertexBufferBinding();
            vbo.references = 1;
            return vbo;
        };
        /**
         * Update a dynamic index buffer
         * @param indexBuffer defines the target index buffer
         * @param indices defines the data to update
         * @param offset defines the offset in the target index buffer where update should start
         */
        Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
            if (offset === void 0) { offset = 0; }
            // Force cache update
            this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
            this.bindIndexBuffer(indexBuffer);
            var arrayBuffer;
            if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
                arrayBuffer = indices;
            }
            else {
                arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
            }
            this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
            this._resetIndexBufferBinding();
        };
        /**
         * Updates a dynamic vertex buffer.
         * @param vertexBuffer the vertex buffer to update
         * @param data the data used to update the vertex buffer
         * @param byteOffset the byte offset of the data
         * @param byteLength the byte length of the data
         */
        Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
            this.bindArrayBuffer(vertexBuffer);
            if (byteOffset === undefined) {
                byteOffset = 0;
            }
            if (byteLength === undefined) {
                if (data instanceof Array) {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
                }
                else {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
                }
            }
            else {
                if (data instanceof Array) {
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
                }
                else {
                    if (data instanceof ArrayBuffer) {
                        data = new Uint8Array(data, byteOffset, byteLength);
                    }
                    else {
                        data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
                    }
                    this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
                }
            }
            this._resetVertexBufferBinding();
        };
        Engine.prototype._resetIndexBufferBinding = function () {
            this.bindIndexBuffer(null);
            this._cachedIndexBuffer = null;
        };
        /**
         * Creates a new index buffer
         * @param indices defines the content of the index buffer
         * @param updatable defines if the index buffer must be updatable
         * @returns a new webGL buffer
         */
        Engine.prototype.createIndexBuffer = function (indices, updatable) {
            var vbo = this._gl.createBuffer();
            if (!vbo) {
                throw new Error("Unable to create index buffer");
            }
            this.bindIndexBuffer(vbo);
            // Check for 32 bits indices
            var arrayBuffer;
            var need32Bits = false;
            if (indices instanceof Uint16Array) {
                arrayBuffer = indices;
            }
            else {
                //check 32 bit support
                if (this._caps.uintIndices) {
                    if (indices instanceof Uint32Array) {
                        arrayBuffer = indices;
                        need32Bits = true;
                    }
                    else {
                        //number[] or Int32Array, check if 32 bit is necessary
                        for (var index = 0; index < indices.length; index++) {
                            if (indices[index] > 65535) {
                                need32Bits = true;
                                break;
                            }
                        }
                        arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
                    }
                }
                else {
                    //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
                    arrayBuffer = new Uint16Array(indices);
                }
            }
            this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
            this._resetIndexBufferBinding();
            vbo.references = 1;
            vbo.is32Bits = need32Bits;
            return vbo;
        };
        /**
         * Bind a webGL buffer to the webGL context
         * @param buffer defines the buffer to bind
         */
        Engine.prototype.bindArrayBuffer = function (buffer) {
            if (!this._vaoRecordInProgress) {
                this._unbindVertexArrayObject();
            }
            this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
        };
        /**
         * Bind an uniform buffer to the current webGL context
         * @param buffer defines the buffer to bind
         */
        Engine.prototype.bindUniformBuffer = function (buffer) {
            this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
        };
        /**
         * Bind a buffer to the current webGL context at a given location
         * @param buffer defines the buffer to bind
         * @param location defines the index where to bind the buffer
         */
        Engine.prototype.bindUniformBufferBase = function (buffer, location) {
            this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
        };
        /**
         * Bind a specific block at a given index in a specific shader program
         * @param shaderProgram defines the shader program
         * @param blockName defines the block name
         * @param index defines the index where to bind the block
         */
        Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
            var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
            this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
        };
        Engine.prototype.bindIndexBuffer = function (buffer) {
            if (!this._vaoRecordInProgress) {
                this._unbindVertexArrayObject();
            }
            this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
        };
        Engine.prototype.bindBuffer = function (buffer, target) {
            if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
                this._gl.bindBuffer(target, buffer);
                this._currentBoundBuffer[target] = buffer;
            }
        };
        /**
         * update the bound buffer with the given data
         * @param data defines the data to update
         */
        Engine.prototype.updateArrayBuffer = function (data) {
            this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
        };
        Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
            var pointer = this._currentBufferPointers[indx];
            var changed = false;
            if (!pointer.active) {
                changed = true;
                pointer.active = true;
                pointer.index = indx;
                pointer.size = size;
                pointer.type = type;
                pointer.normalized = normalized;
                pointer.stride = stride;
                pointer.offset = offset;
                pointer.buffer = buffer;
            }
            else {
                if (pointer.buffer !== buffer) {
                    pointer.buffer = buffer;
                    changed = true;
                }
                if (pointer.size !== size) {
                    pointer.size = size;
                    changed = true;
                }
                if (pointer.type !== type) {
                    pointer.type = type;
                    changed = true;
                }
                if (pointer.normalized !== normalized) {
                    pointer.normalized = normalized;
                    changed = true;
                }
                if (pointer.stride !== stride) {
                    pointer.stride = stride;
                    changed = true;
                }
                if (pointer.offset !== offset) {
                    pointer.offset = offset;
                    changed = true;
                }
            }
            if (changed || this._vaoRecordInProgress) {
                this.bindArrayBuffer(buffer);
                this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
            }
        };
        Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
            if (indexBuffer == null) {
                return;
            }
            if (this._cachedIndexBuffer !== indexBuffer) {
                this._cachedIndexBuffer = indexBuffer;
                this.bindIndexBuffer(indexBuffer);
                this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
            }
        };
        Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
            var attributes = effect.getAttributesNames();
            if (!this._vaoRecordInProgress) {
                this._unbindVertexArrayObject();
            }
            this.unbindAllAttributes();
            for (var index = 0; index < attributes.length; index++) {
                var order = effect.getAttributeLocation(index);
                if (order >= 0) {
                    var vertexBuffer = vertexBuffers[attributes[index]];
                    if (!vertexBuffer) {
                        continue;
                    }
                    this._gl.enableVertexAttribArray(order);
                    if (!this._vaoRecordInProgress) {
                        this._vertexAttribArraysEnabled[order] = true;
                    }
                    var buffer = vertexBuffer.getBuffer();
                    if (buffer) {
                        this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
                        if (vertexBuffer.getIsInstanced()) {
                            this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
                            if (!this._vaoRecordInProgress) {
                                this._currentInstanceLocations.push(order);
                                this._currentInstanceBuffers.push(buffer);
                            }
                        }
                    }
                }
            }
        };
        /**
         * Records a vertex array object
         * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
         * @param vertexBuffers defines the list of vertex buffers to store
         * @param indexBuffer defines the index buffer to store
         * @param effect defines the effect to store
         * @returns the new vertex array object
         */
        Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
            var vao = this._gl.createVertexArray();
            this._vaoRecordInProgress = true;
            this._gl.bindVertexArray(vao);
            this._mustWipeVertexAttributes = true;
            this._bindVertexBuffersAttributes(vertexBuffers, effect);
            this.bindIndexBuffer(indexBuffer);
            this._vaoRecordInProgress = false;
            this._gl.bindVertexArray(null);
            return vao;
        };
        /**
         * Bind a specific vertex array object
         * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
         * @param vertexArrayObject defines the vertex array object to bind
         * @param indexBuffer defines the index buffer to bind
         */
        Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
            if (this._cachedVertexArrayObject !== vertexArrayObject) {
                this._cachedVertexArrayObject = vertexArrayObject;
                this._gl.bindVertexArray(vertexArrayObject);
                this._cachedVertexBuffers = null;
                this._cachedIndexBuffer = null;
                this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
                this._mustWipeVertexAttributes = true;
            }
        };
        /**
         * Bind webGl buffers directly to the webGL context
         * @param vertexBuffer defines the vertex buffer to bind
         * @param indexBuffer defines the index buffer to bind
         * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
         * @param vertexStrideSize defines the vertex stride of the vertex buffer
         * @param effect defines the effect associated with the vertex buffer
         */
        Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
            if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
                this._cachedVertexBuffers = vertexBuffer;
                this._cachedEffectForVertexBuffers = effect;
                var attributesCount = effect.getAttributesCount();
                this._unbindVertexArrayObject();
                this.unbindAllAttributes();
                var offset = 0;
                for (var index = 0; index < attributesCount; index++) {
                    if (index < vertexDeclaration.length) {
                        var order = effect.getAttributeLocation(index);
                        if (order >= 0) {
                            this._gl.enableVertexAttribArray(order);
                            this._vertexAttribArraysEnabled[order] = true;
                            this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
                        }
                        offset += vertexDeclaration[index] * 4;
                    }
                }
            }
            this._bindIndexBufferWithCache(indexBuffer);
        };
        Engine.prototype._unbindVertexArrayObject = function () {
            if (!this._cachedVertexArrayObject) {
                return;
            }
            this._cachedVertexArrayObject = null;
            this._gl.bindVertexArray(null);
        };
        /**
         * Bind a list of vertex buffers to the webGL context
         * @param vertexBuffers defines the list of vertex buffers to bind
         * @param indexBuffer defines the index buffer to bind
         * @param effect defines the effect associated with the vertex buffers
         */
        Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
            if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
                this._cachedVertexBuffers = vertexBuffers;
                this._cachedEffectForVertexBuffers = effect;
                this._bindVertexBuffersAttributes(vertexBuffers, effect);
            }
            this._bindIndexBufferWithCache(indexBuffer);
        };
        /**
         * Unbind all instance attributes
         */
        Engine.prototype.unbindInstanceAttributes = function () {
            var boundBuffer;
            for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
                var instancesBuffer = this._currentInstanceBuffers[i];
                if (boundBuffer != instancesBuffer && instancesBuffer.references) {
                    boundBuffer = instancesBuffer;
                    this.bindArrayBuffer(instancesBuffer);
                }
                var offsetLocation = this._currentInstanceLocations[i];
                this._gl.vertexAttribDivisor(offsetLocation, 0);
            }
            this._currentInstanceBuffers.length = 0;
            this._currentInstanceLocations.length = 0;
        };
        /**
         * Release and free the memory of a vertex array object
         * @param vao defines the vertex array object to delete
         */
        Engine.prototype.releaseVertexArrayObject = function (vao) {
            this._gl.deleteVertexArray(vao);
        };
        /** @hidden */
        Engine.prototype._releaseBuffer = function (buffer) {
            buffer.references--;
            if (buffer.references === 0) {
                this._gl.deleteBuffer(buffer);
                return true;
            }
            return false;
        };
        /**
         * Creates a webGL buffer to use with instanciation
         * @param capacity defines the size of the buffer
         * @returns the webGL buffer
         */
        Engine.prototype.createInstancesBuffer = function (capacity) {
            var buffer = this._gl.createBuffer();
            if (!buffer) {
                throw new Error("Unable to create instance buffer");
            }
            buffer.capacity = capacity;
            this.bindArrayBuffer(buffer);
            this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
            return buffer;
        };
        /**
         * Delete a webGL buffer used with instanciation
         * @param buffer defines the webGL buffer to delete
         */
        Engine.prototype.deleteInstancesBuffer = function (buffer) {
            this._gl.deleteBuffer(buffer);
        };
        /**
         * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
         * @param instancesBuffer defines the webGL buffer to update and bind
         * @param data defines the data to store in the buffer
         * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
         */
        Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
            this.bindArrayBuffer(instancesBuffer);
            if (data) {
                this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
            }
            if (offsetLocations[0].index !== undefined) {
                var stride = 0;
                for (var i = 0; i < offsetLocations.length; i++) {
                    var ai = offsetLocations[i];
                    stride += ai.attributeSize * 4;
                }
                for (var i = 0; i < offsetLocations.length; i++) {
                    var ai = offsetLocations[i];
                    if (!this._vertexAttribArraysEnabled[ai.index]) {
                        this._gl.enableVertexAttribArray(ai.index);
                        this._vertexAttribArraysEnabled[ai.index] = true;
                    }
                    this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
                    this._gl.vertexAttribDivisor(ai.index, 1);
                    this._currentInstanceLocations.push(ai.index);
                    this._currentInstanceBuffers.push(instancesBuffer);
                }
            }
            else {
                for (var index = 0; index < 4; index++) {
                    var offsetLocation = offsetLocations[index];
                    if (!this._vertexAttribArraysEnabled[offsetLocation]) {
                        this._gl.enableVertexAttribArray(offsetLocation);
                        this._vertexAttribArraysEnabled[offsetLocation] = true;
                    }
                    this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
                    this._gl.vertexAttribDivisor(offsetLocation, 1);
                    this._currentInstanceLocations.push(offsetLocation);
                    this._currentInstanceBuffers.push(instancesBuffer);
                }
            }
        };
        /**
         * Apply all cached states (depth, culling, stencil and alpha)
         */
        Engine.prototype.applyStates = function () {
            this._depthCullingState.apply(this._gl);
            this._stencilState.apply(this._gl);
            this._alphaState.apply(this._gl);
        };
        /**
         * Send a draw order
         * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
         * @param indexStart defines the starting index
         * @param indexCount defines the number of index to draw
         * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
         */
        Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
            this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
        };
        /**
         * Draw a list of points
         * @param verticesStart defines the index of first vertex to draw
         * @param verticesCount defines the count of vertices to draw
         * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
         */
        Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
            this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
        };
        /**
         * Draw a list of unindexed primitives
         * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
         * @param verticesStart defines the index of first vertex to draw
         * @param verticesCount defines the count of vertices to draw
         * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
         */
        Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
            this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
        };
        /**
         * Draw a list of indexed primitives
         * @param fillMode defines the primitive to use
         * @param indexStart defines the starting index
         * @param indexCount defines the number of index to draw
         * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
         */
        Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
            // Apply states
            this.applyStates();
            this._drawCalls.addCount(1, false);
            // Render
            var drawMode = this._drawMode(fillMode);
            var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
            var mult = this._uintIndicesCurrentlySet ? 4 : 2;
            if (instancesCount) {
                this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
            }
            else {
                this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
            }
        };
        /**
         * Draw a list of unindexed primitives
         * @param fillMode defines the primitive to use
         * @param verticesStart defines the index of first vertex to draw
         * @param verticesCount defines the count of vertices to draw
         * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
         */
        Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
            // Apply states
            this.applyStates();
            this._drawCalls.addCount(1, false);
            var drawMode = this._drawMode(fillMode);
            if (instancesCount) {
                this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
            }
            else {
                this._gl.drawArrays(drawMode, verticesStart, verticesCount);
            }
        };
        Engine.prototype._drawMode = function (fillMode) {
            switch (fillMode) {
                // Triangle views
                case BABYLON.Material.TriangleFillMode:
                    return this._gl.TRIANGLES;
                case BABYLON.Material.PointFillMode:
                    return this._gl.POINTS;
                case BABYLON.Material.WireFrameFillMode:
                    return this._gl.LINES;
                // Draw modes
                case BABYLON.Material.PointListDrawMode:
                    return this._gl.POINTS;
                case BABYLON.Material.LineListDrawMode:
                    return this._gl.LINES;
                case BABYLON.Material.LineLoopDrawMode:
                    return this._gl.LINE_LOOP;
                case BABYLON.Material.LineStripDrawMode:
                    return this._gl.LINE_STRIP;
                case BABYLON.Material.TriangleStripDrawMode:
                    return this._gl.TRIANGLE_STRIP;
                case BABYLON.Material.TriangleFanDrawMode:
                    return this._gl.TRIANGLE_FAN;
                default:
                    return this._gl.TRIANGLES;
            }
        };
        // Shaders
        /** @hidden */
        Engine.prototype._releaseEffect = function (effect) {
            if (this._compiledEffects[effect._key]) {
                delete this._compiledEffects[effect._key];
                this._deleteProgram(effect.getProgram());
            }
        };
        /** @hidden */
        Engine.prototype._deleteProgram = function (program) {
            if (program) {
                program.__SPECTOR_rebuildProgram = null;
                if (program.transformFeedback) {
                    this.deleteTransformFeedback(program.transformFeedback);
                    program.transformFeedback = null;
                }
                this._gl.deleteProgram(program);
            }
        };
        /**
         * Create a new effect (used to store vertex/fragment shaders)
         * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
         * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
         * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
         * @param samplers defines an array of string used to represent textures
         * @param defines defines the string containing the defines to use to compile the shaders
         * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
         * @param onCompiled defines a function to call when the effect creation is successful
         * @param onError defines a function to call when the effect creation has failed
         * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
         * @returns the new Effect
         */
        Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
            var vertex = baseName.vertexElement || baseName.vertex || baseName;
            var fragment = baseName.fragmentElement || baseName.fragment || baseName;
            var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
            if (this._compiledEffects[name]) {
                var compiledEffect = this._compiledEffects[name];
                if (onCompiled && compiledEffect.isReady()) {
                    onCompiled(compiledEffect);
                }
                return compiledEffect;
            }
            var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
            effect._key = name;
            this._compiledEffects[name] = effect;
            return effect;
        };
        Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
            return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
        };
        Engine.prototype._compileRawShader = function (source, type) {
            var gl = this._gl;
            var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
            if (!shader) {
                throw new Error("Something went wrong while compile the shader.");
            }
            gl.shaderSource(shader, source);
            gl.compileShader(shader);
            if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
                var log = gl.getShaderInfoLog(shader);
                if (log) {
                    throw new Error(log);
                }
            }
            return shader;
        };
        /**
         * Directly creates a webGL program
         * @param vertexCode defines the vertex shader code to use
         * @param fragmentCode defines the fragment shader code to use
         * @param context defines the webGL context to use (if not set, the current one will be used)
         * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
         * @returns the new webGL program
         */
        Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
            if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
            context = context || this._gl;
            var vertexShader = this._compileRawShader(vertexCode, "vertex");
            var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
            return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
        };
        /**
         * Creates a webGL program
         * @param vertexCode  defines the vertex shader code to use
         * @param fragmentCode defines the fragment shader code to use
         * @param defines defines the string containing the defines to use to compile the shaders
         * @param context defines the webGL context to use (if not set, the current one will be used)
         * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
         * @returns the new webGL program
         */
        Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
            if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
            context = context || this._gl;
            this.onBeforeShaderCompilationObservable.notifyObservers(this);
            var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
            var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
            var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
            var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
            this.onAfterShaderCompilationObservable.notifyObservers(this);
            return program;
        };
        Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
            if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
            var shaderProgram = context.createProgram();
            if (!shaderProgram) {
                throw new Error("Unable to create program");
            }
            context.attachShader(shaderProgram, vertexShader);
            context.attachShader(shaderProgram, fragmentShader);
            if (this.webGLVersion > 1 && transformFeedbackVaryings) {
                var transformFeedback = this.createTransformFeedback();
                this.bindTransformFeedback(transformFeedback);
                this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
                shaderProgram.transformFeedback = transformFeedback;
            }
            context.linkProgram(shaderProgram);
            if (this.webGLVersion > 1 && transformFeedbackVaryings) {
                this.bindTransformFeedback(null);
            }
            var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
            if (!linked) {
                var error = context.getProgramInfoLog(shaderProgram);
                if (error) {
                    throw new Error(error);
                }
            }
            if (this.validateShaderPrograms) {
                context.validateProgram(shaderProgram);
                var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
                if (!validated) {
                    var error = context.getProgramInfoLog(shaderProgram);
                    if (error) {
                        throw new Error(error);
                    }
                }
            }
            context.deleteShader(vertexShader);
            context.deleteShader(fragmentShader);
            return shaderProgram;
        };
        /**
         * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
         * @param shaderProgram defines the webGL program to use
         * @param uniformsNames defines the list of uniform names
         * @returns an array of webGL uniform locations
         */
        Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
            var results = new Array();
            for (var index = 0; index < uniformsNames.length; index++) {
                results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
            }
            return results;
        };
        /**
         * Gets the lsit of active attributes for a given webGL program
         * @param shaderProgram defines the webGL program to use
         * @param attributesNames defines the list of attribute names to get
         * @returns an array of indices indicating the offset of each attribute
         */
        Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
            var results = [];
            for (var index = 0; index < attributesNames.length; index++) {
                try {
                    results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
                }
                catch (e) {
                    results.push(-1);
                }
            }
            return results;
        };
        /**
         * Activates an effect, mkaing it the current one (ie. the one used for rendering)
         * @param effect defines the effect to activate
         */
        Engine.prototype.enableEffect = function (effect) {
            if (!effect || effect === this._currentEffect) {
                return;
            }
            // Use program
            this.bindSamplers(effect);
            this._currentEffect = effect;
            if (effect.onBind) {
                effect.onBind(effect);
            }
            if (effect._onBindObservable) {
                effect._onBindObservable.notifyObservers(effect);
            }
        };
        /**
         * Set the value of an uniform to an array of int32
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of int32 to store
         */
        Engine.prototype.setIntArray = function (uniform, array) {
            if (!uniform) {
                return;
            }
            this._gl.uniform1iv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of int32 (stored as vec2)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of int32 to store
         */
        Engine.prototype.setIntArray2 = function (uniform, array) {
            if (!uniform || array.length % 2 !== 0) {
                return;
            }
            this._gl.uniform2iv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of int32 (stored as vec3)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of int32 to store
         */
        Engine.prototype.setIntArray3 = function (uniform, array) {
            if (!uniform || array.length % 3 !== 0) {
                return;
            }
            this._gl.uniform3iv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of int32 (stored as vec4)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of int32 to store
         */
        Engine.prototype.setIntArray4 = function (uniform, array) {
            if (!uniform || array.length % 4 !== 0) {
                return;
            }
            this._gl.uniform4iv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of float32
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of float32 to store
         */
        Engine.prototype.setFloatArray = function (uniform, array) {
            if (!uniform) {
                return;
            }
            this._gl.uniform1fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of float32 (stored as vec2)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of float32 to store
         */
        Engine.prototype.setFloatArray2 = function (uniform, array) {
            if (!uniform || array.length % 2 !== 0) {
                return;
            }
            this._gl.uniform2fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of float32 (stored as vec3)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of float32 to store
         */
        Engine.prototype.setFloatArray3 = function (uniform, array) {
            if (!uniform || array.length % 3 !== 0) {
                return;
            }
            this._gl.uniform3fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of float32 (stored as vec4)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of float32 to store
         */
        Engine.prototype.setFloatArray4 = function (uniform, array) {
            if (!uniform || array.length % 4 !== 0) {
                return;
            }
            this._gl.uniform4fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of number
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of number to store
         */
        Engine.prototype.setArray = function (uniform, array) {
            if (!uniform) {
                return;
            }
            this._gl.uniform1fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of number (stored as vec2)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of number to store
         */
        Engine.prototype.setArray2 = function (uniform, array) {
            if (!uniform || array.length % 2 !== 0) {
                return;
            }
            this._gl.uniform2fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of number (stored as vec3)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of number to store
         */
        Engine.prototype.setArray3 = function (uniform, array) {
            if (!uniform || array.length % 3 !== 0) {
                return;
            }
            this._gl.uniform3fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of number (stored as vec4)
         * @param uniform defines the webGL uniform location where to store the value
         * @param array defines the array of number to store
         */
        Engine.prototype.setArray4 = function (uniform, array) {
            if (!uniform || array.length % 4 !== 0) {
                return;
            }
            this._gl.uniform4fv(uniform, array);
        };
        /**
         * Set the value of an uniform to an array of float32 (stored as matrices)
         * @param uniform defines the webGL uniform location where to store the value
         * @param matrices defines the array of float32 to store
         */
        Engine.prototype.setMatrices = function (uniform, matrices) {
            if (!uniform) {
                return;
            }
            this._gl.uniformMatrix4fv(uniform, false, matrices);
        };
        /**
         * Set the value of an uniform to a matrix
         * @param uniform defines the webGL uniform location where to store the value
         * @param matrix defines the matrix to store
         */
        Engine.prototype.setMatrix = function (uniform, matrix) {
            if (!uniform) {
                return;
            }
            this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
        };
        /**
         * Set the value of an uniform to a matrix (3x3)
         * @param uniform defines the webGL uniform location where to store the value
         * @param matrix defines the Float32Array representing the 3x3 matrix to store
         */
        Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
            if (!uniform) {
                return;
            }
            this._gl.uniformMatrix3fv(uniform, false, matrix);
        };
        /**
         * Set the value of an uniform to a matrix (2x2)
         * @param uniform defines the webGL uniform location where to store the value
         * @param matrix defines the Float32Array representing the 2x2 matrix to store
         */
        Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
            if (!uniform) {
                return;
            }
            this._gl.uniformMatrix2fv(uniform, false, matrix);
        };
        /**
         * Set the value of an uniform to a number (int)
         * @param uniform defines the webGL uniform location where to store the value
         * @param value defines the int number to store
         */
        Engine.prototype.setInt = function (uniform, value) {
            if (!uniform) {
                return;
            }
            this._gl.uniform1i(uniform, value);
        };
        /**
         * Set the value of an uniform to a number (float)
         * @param uniform defines the webGL uniform location where to store the value
         * @param value defines the float number to store
         */
        Engine.prototype.setFloat = function (uniform, value) {
            if (!uniform) {
                return;
            }
            this._gl.uniform1f(uniform, value);
        };
        /**
         * Set the value of an uniform to a vec2
         * @param uniform defines the webGL uniform location where to store the value
         * @param x defines the 1st component of the value
         * @param y defines the 2nd component of the value
         */
        Engine.prototype.setFloat2 = function (uniform, x, y) {
            if (!uniform) {
                return;
            }
            this._gl.uniform2f(uniform, x, y);
        };
        /**
         * Set the value of an uniform to a vec3
         * @param uniform defines the webGL uniform location where to store the value
         * @param x defines the 1st component of the value
         * @param y defines the 2nd component of the value
         * @param z defines the 3rd component of the value
         */
        Engine.prototype.setFloat3 = function (uniform, x, y, z) {
            if (!uniform) {
                return;
            }
            this._gl.uniform3f(uniform, x, y, z);
        };
        /**
         * Set the value of an uniform to a boolean
         * @param uniform defines the webGL uniform location where to store the value
         * @param bool defines the boolean to store
         */
        Engine.prototype.setBool = function (uniform, bool) {
            if (!uniform) {
                return;
            }
            this._gl.uniform1i(uniform, bool);
        };
        /**
         * Set the value of an uniform to a vec4
         * @param uniform defines the webGL uniform location where to store the value
         * @param x defines the 1st component of the value
         * @param y defines the 2nd component of the value
         * @param z defines the 3rd component of the value
         * @param w defines the 4th component of the value
         */
        Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
            if (!uniform) {
                return;
            }
            this._gl.uniform4f(uniform, x, y, z, w);
        };
        /**
         * Set the value of an uniform to a Color3
         * @param uniform defines the webGL uniform location where to store the value
         * @param color3 defines the color to store
         */
        Engine.prototype.setColor3 = function (uniform, color3) {
            if (!uniform) {
                return;
            }
            this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
        };
        /**
         * Set the value of an uniform to a Color3 and an alpha value
         * @param uniform defines the webGL uniform location where to store the value
         * @param color3 defines the color to store
         * @param alpha defines the alpha component to store
         */
        Engine.prototype.setColor4 = function (uniform, color3, alpha) {
            if (!uniform) {
                return;
            }
            this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
        };
        /**
         * Sets a Color4 on a uniform variable
         * @param uniform defines the uniform location
         * @param color4 defines the value to be set
         */
        Engine.prototype.setDirectColor4 = function (uniform, color4) {
            if (!uniform) {
                return;
            }
            this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
        };
        // States
        /**
         * Set various states to the webGL context
         * @param culling defines backface culling state
         * @param zOffset defines the value to apply to zOffset (0 by default)
         * @param force defines if states must be applied even if cache is up to date
         * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
         */
        Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
            if (zOffset === void 0) { zOffset = 0; }
            if (reverseSide === void 0) { reverseSide = false; }
            // Culling
            if (this._depthCullingState.cull !== culling || force) {
                this._depthCullingState.cull = culling;
            }
            // Cull face
            var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
            if (this._depthCullingState.cullFace !== cullFace || force) {
                this._depthCullingState.cullFace = cullFace;
            }
            // Z offset
            this.setZOffset(zOffset);
            // Front face
            var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
            if (this._depthCullingState.frontFace !== frontFace || force) {
                this._depthCullingState.frontFace = frontFace;
            }
        };
        /**
         * Set the z offset to apply to current rendering
         * @param value defines the offset to apply
         */
        Engine.prototype.setZOffset = function (value) {
            this._depthCullingState.zOffset = value;
        };
        /**
         * Gets the current value of the zOffset
         * @returns the current zOffset state
         */
        Engine.prototype.getZOffset = function () {
            return this._depthCullingState.zOffset;
        };
        /**
         * Enable or disable depth buffering
         * @param enable defines the state to set
         */
        Engine.prototype.setDepthBuffer = function (enable) {
            this._depthCullingState.depthTest = enable;
        };
        /**
         * Gets a boolean indicating if depth writing is enabled
         * @returns the current depth writing state
         */
        Engine.prototype.getDepthWrite = function () {
            return this._depthCullingState.depthMask;
        };
        /**
         * Enable or disable depth writing
         * @param enable defines the state to set
         */
        Engine.prototype.setDepthWrite = function (enable) {
            this._depthCullingState.depthMask = enable;
        };
        /**
         * Enable or disable color writing
         * @param enable defines the state to set
         */
        Engine.prototype.setColorWrite = function (enable) {
            this._gl.colorMask(enable, enable, enable, enable);
            this._colorWrite = enable;
        };
        /**
         * Gets a boolean indicating if color writing is enabled
         * @returns the current color writing state
         */
        Engine.prototype.getColorWrite = function () {
            return this._colorWrite;
        };
        /**
         * Sets alpha constants used by some alpha blending modes
         * @param r defines the red component
         * @param g defines the green component
         * @param b defines the blue component
         * @param a defines the alpha component
         */
        Engine.prototype.setAlphaConstants = function (r, g, b, a) {
            this._alphaState.setAlphaBlendConstants(r, g, b, a);
        };
        /**
         * Sets the current alpha mode
         * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
         * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
         * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
         */
        Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
            if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
            if (this._alphaMode === mode) {
                return;
            }
            switch (mode) {
                case Engine.ALPHA_DISABLE:
                    this._alphaState.alphaBlend = false;
                    break;
                case Engine.ALPHA_PREMULTIPLIED:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_COMBINE:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_ONEONE:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_ADD:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_SUBTRACT:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_MULTIPLY:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_MAXIMIZED:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_INTERPOLATE:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
                    this._alphaState.alphaBlend = true;
                    break;
                case Engine.ALPHA_SCREENMODE:
                    this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
                    this._alphaState.alphaBlend = true;
                    break;
            }
            if (!noDepthWriteChange) {
                this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
            }
            this._alphaMode = mode;
        };
        /**
         * Gets the current alpha mode
         * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
         * @returns the current alpha mode
         */
        Engine.prototype.getAlphaMode = function () {
            return this._alphaMode;
        };
        // Textures
        /**
         * Clears the list of texture accessible through engine.
         * This can help preventing texture load conflict due to name collision.
         */
        Engine.prototype.clearInternalTexturesCache = function () {
            this._internalTexturesCache = [];
        };
        /**
         * Force the entire cache to be cleared
         * You should not have to use this function unless your engine needs to share the webGL context with another engine
         * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
         */
        Engine.prototype.wipeCaches = function (bruteForce) {
            if (this.preventCacheWipeBetweenFrames && !bruteForce) {
                return;
            }
            this._currentEffect = null;
            this._viewportCached.x = 0;
            this._viewportCached.y = 0;
            this._viewportCached.z = 0;
            this._viewportCached.w = 0;
            if (bruteForce) {
                this.resetTextureCache();
                this._currentProgram = null;
                this._stencilState.reset();
                this._depthCullingState.reset();
                this.setDepthFunctionToLessOrEqual();
                this._alphaState.reset();
                this._unpackFlipYCached = null;
            }
            this._resetVertexBufferBinding();
            this._cachedIndexBuffer = null;
            this._cachedEffectForVertexBuffers = null;
            this._unbindVertexArrayObject();
            this.bindIndexBuffer(null);
        };
        /**
         * Set the compressed texture format to use, based on the formats you have, and the formats
         * supported by the hardware / browser.
         *
         * Khronos Texture Container (.ktx) files are used to support this.  This format has the
         * advantage of being specifically designed for OpenGL.  Header elements directly correspond
         * to API arguments needed to compressed textures.  This puts the burden on the container
         * generator to house the arcane code for determining these for current & future formats.
         *
         * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
         * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
         *
         * Note: The result of this call is not taken into account when a texture is base64.
         *
         * @param formatsAvailable defines the list of those format families you have created
         * on your server.  Syntax: '-' + format family + '.ktx'.  (Case and order do not matter.)
         *
         * Current families are astc, dxt, pvrtc, etc2, & etc1.
         * @returns The extension selected.
         */
        Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
            for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
                for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
                    if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
                        return this._textureFormatInUse = this._texturesSupported[i];
                    }
                }
            }
            // actively set format to nothing, to allow this to be called more than once
            // and possibly fail the 2nd time
            this._textureFormatInUse = null;
            return null;
        };
        Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
            var gl = this._gl;
            var magFilter = gl.NEAREST;
            var minFilter = gl.NEAREST;
            switch (samplingMode) {
                case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
                    magFilter = gl.LINEAR;
                    if (generateMipMaps) {
                        minFilter = gl.LINEAR_MIPMAP_NEAREST;
                    }
                    else {
                        minFilter = gl.LINEAR;
                    }
                    break;
                case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
                    magFilter = gl.LINEAR;
                    if (generateMipMaps) {
                        minFilter = gl.LINEAR_MIPMAP_LINEAR;
                    }
                    else {
                        minFilter = gl.LINEAR;
                    }
                    break;
                case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
                    magFilter = gl.NEAREST;
                    if (generateMipMaps) {
                        minFilter = gl.NEAREST_MIPMAP_LINEAR;
                    }
                    else {
                        minFilter = gl.NEAREST;
                    }
                    break;
                case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
                    magFilter = gl.NEAREST;
                    if (generateMipMaps) {
                        minFilter = gl.NEAREST_MIPMAP_NEAREST;
                    }
                    else {
                        minFilter = gl.NEAREST;
                    }
                    break;
                case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
                    magFilter = gl.NEAREST;
                    if (generateMipMaps) {
                        minFilter = gl.LINEAR_MIPMAP_NEAREST;
                    }
                    else {
                        minFilter = gl.LINEAR;
                    }
                    break;
                case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
                    magFilter = gl.NEAREST;
                    if (generateMipMaps) {
                        minFilter = gl.LINEAR_MIPMAP_LINEAR;
                    }
                    else {
                        minFilter = gl.LINEAR;
                    }
                    break;
                case Engine.TEXTURE_NEAREST_LINEAR:
                    magFilter = gl.NEAREST;
                    minFilter = gl.LINEAR;
                    break;
                case Engine.TEXTURE_NEAREST_NEAREST:
                    magFilter = gl.NEAREST;
                    minFilter = gl.NEAREST;
                    break;
                case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
                    magFilter = gl.LINEAR;
                    if (generateMipMaps) {
                        minFilter = gl.NEAREST_MIPMAP_NEAREST;
                    }
                    else {
                        minFilter = gl.NEAREST;
                    }
                    break;
                case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
                    magFilter = gl.LINEAR;
                    if (generateMipMaps) {
                        minFilter = gl.NEAREST_MIPMAP_LINEAR;
                    }
                    else {
                        minFilter = gl.NEAREST;
                    }
                    break;
                case Engine.TEXTURE_LINEAR_LINEAR:
                    magFilter = gl.LINEAR;
                    minFilter = gl.LINEAR;
                    break;
                case Engine.TEXTURE_LINEAR_NEAREST:
                    magFilter = gl.LINEAR;
                    minFilter = gl.NEAREST;
                    break;
            }
            return {
                min: minFilter,
                mag: magFilter
            };
        };
        Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
            if (onErrorCallBack === void 0) { onErrorCallBack = null; }
            var img;
            var onload = function () {
                loadedImages[index] = img;
                loadedImages._internalCount++;
                if (scene) {
                    scene._removePendingData(img);
                }
                if (loadedImages._internalCount === 6) {
                    onfinish(loadedImages);
                }
            };
            var onerror = function (message, exception) {
                if (scene) {
                    scene._removePendingData(img);
                }
                if (onErrorCallBack) {
                    onErrorCallBack(message, exception);
                }
            };
            img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
            if (scene) {
                scene._addPendingData(img);
            }
        };
        Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
            if (onError === void 0) { onError = null; }
            var loadedImages = [];
            loadedImages._internalCount = 0;
            for (var index = 0; index < 6; index++) {
                this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
            }
        };
        /** @hidden */
        Engine.prototype._createTexture = function () {
            var texture = this._gl.createTexture();
            if (!texture) {
                throw new Error("Unable to create texture");
            }
            return texture;
        };
        /**
         * Usually called from BABYLON.Texture.ts.
         * Passed information to create a WebGLTexture
         * @param urlArg defines a value which contains one of the following:
         * * A conventional http URL, e.g. 'http://...' or 'file://...'
         * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
         * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
         * @param noMipmap defines a boolean indicating that no mipmaps shall be generated.  Ignored for compressed textures.  They must be in the file
         * @param invertY when true, image is flipped when loaded.  You probably want true. Ignored for compressed textures.  Must be flipped in the file
         * @param scene needed for loading to the correct scene
         * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
         * @param onLoad optional callback to be called upon successful completion
         * @param onError optional callback to be called upon failure
         * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
         * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
         * @param format internal format.  Default: RGB when extension is '.jpg' else RGBA.  Ignored for compressed textures
         * @param forcedExtension defines the extension to use to pick the right loader
         * @returns a InternalTexture for assignment back into BABYLON.Texture
         */
        Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
            var _this = this;
            if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (buffer === void 0) { buffer = null; }
            if (fallback === void 0) { fallback = null; }
            if (format === void 0) { format = null; }
            if (forcedExtension === void 0) { forcedExtension = null; }
            var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
            var fromData = url.substr(0, 5) === "data:";
            var fromBlob = url.substr(0, 5) === "blob:";
            var isBase64 = fromData && url.indexOf(";base64,") !== -1;
            var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
            // establish the file extension, if possible
            var lastDot = url.lastIndexOf('.');
            var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
            var loader = null;
            for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
                var availableLoader = _a[_i];
                if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
                    loader = availableLoader;
                    break;
                }
            }
            if (loader) {
                url = loader.transformUrl(url, this._textureFormatInUse);
            }
            if (scene) {
                scene._addPendingData(texture);
            }
            texture.url = url;
            texture.generateMipMaps = !noMipmap;
            texture.samplingMode = samplingMode;
            texture.invertY = invertY;
            if (!this._doNotHandleContextLost) {
                // Keep a link to the buffer only if we plan to handle context lost
                texture._buffer = buffer;
            }
            var onLoadObserver = null;
            if (onLoad && !fallback) {
                onLoadObserver = texture.onLoadedObservable.add(onLoad);
            }
            if (!fallback) {
                this._internalTexturesCache.push(texture);
            }
            var onInternalError = function (message, exception) {
                if (scene) {
                    scene._removePendingData(texture);
                }
                var customFallback = false;
                if (loader) {
                    var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
                    if (fallbackUrl) {
                        // Add Back
                        customFallback = true;
                        _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
                    }
                }
                if (!customFallback) {
                    if (onLoadObserver) {
                        texture.onLoadedObservable.remove(onLoadObserver);
                    }
                    if (BABYLON.Tools.UseFallbackTexture) {
                        _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
                    }
                }
                if (onError) {
                    onError(message || "Unknown error", exception);
                }
            };
            // processing for non-image formats
            if (loader) {
                var callback = function (data) {
                    loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
                        _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
                            done();
                            return false;
                        }, samplingMode);
                    });
                };
                if (!buffer) {
                    this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
                        onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
                    });
                }
                else {
                    callback(buffer);
                }
            }
            else {
                var onload = function (img) {
                    if (fromBlob && !_this._doNotHandleContextLost) {
                        // We need to store the image if we need to rebuild the texture
                        // in case of a webgl context lost
                        texture._buffer = img;
                    }
                    _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
                        var gl = _this._gl;
                        var isPot = (img.width === potWidth && img.height === potHeight);
                        var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
                        if (isPot) {
                            gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
                            return false;
                        }
                        var maxTextureSize = _this._caps.maxTextureSize;
                        if (img.width > maxTextureSize || img.height > maxTextureSize) {
                            _this._prepareWorkingCanvas();
                            if (!_this._workingCanvas || !_this._workingContext) {
                                return false;
                            }
                            _this._workingCanvas.width = potWidth;
                            _this._workingCanvas.height = potHeight;
                            _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
                            gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
                            texture.width = potWidth;
                            texture.height = potHeight;
                            return false;
                        }
                        else {
                            // Using shaders when possible to rescale because canvas.drawImage is lossy
                            var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
                            _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
                            gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
                            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
                            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
                            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                            _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
                                _this._releaseTexture(source_1);
                                _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
                                continuationCallback();
                            });
                        }
                        return true;
                    }, samplingMode);
                };
                if (!fromData || isBase64) {
                    if (buffer instanceof HTMLImageElement) {
                        onload(buffer);
                    }
                    else {
                        BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
                    }
                }
                else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
                    BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
                }
                else {
                    onload(buffer);
                }
            }
            return texture;
        };
        Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
            var _this = this;
            var rtt = this.createRenderTargetTexture({
                width: destination.width,
                height: destination.height,
            }, {
                generateMipMaps: false,
                type: Engine.TEXTURETYPE_UNSIGNED_INT,
                samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
                generateDepthBuffer: false,
                generateStencilBuffer: false
            });
            if (!this._rescalePostProcess) {
                this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
            }
            this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
                _this._rescalePostProcess.onApply = function (effect) {
                    effect._bindTexture("textureSampler", source);
                };
                var hostingScene = scene;
                if (!hostingScene) {
                    hostingScene = _this.scenes[_this.scenes.length - 1];
                }
                hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
                _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
                _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
                _this.unBindFramebuffer(rtt);
                _this._releaseTexture(rtt);
                if (onComplete) {
                    onComplete();
                }
            });
        };
        /**
         * Update a raw texture
         * @param texture defines the texture to update
         * @param data defines the data to store in the texture
         * @param format defines the format of the data
         * @param invertY defines if data must be stored with Y axis inverted
         * @param compression defines the compression used (null by default)
         * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
         */
        Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
            if (compression === void 0) { compression = null; }
            if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (!texture) {
                return;
            }
            // babylon's internalSizedFomat but gl's texImage2D internalFormat
            var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
            // babylon's internalFormat but gl's texImage2D format
            var internalFormat = this._getInternalFormat(format);
            var textureType = this._getWebGLTextureType(type);
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
            this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
            if (!this._doNotHandleContextLost) {
                texture._bufferView = data;
                texture.format = format;
                texture.type = type;
                texture.invertY = invertY;
                texture._compression = compression;
            }
            if (texture.width % 4 !== 0) {
                this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
            }
            if (compression && data) {
                this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
            }
            else {
                this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
            }
            if (texture.generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            //  this.resetTextureCache();
            texture.isReady = true;
        };
        /**
         * Creates a raw texture
         * @param data defines the data to store in the texture
         * @param width defines the width of the texture
         * @param height defines the height of the texture
         * @param format defines the format of the data
         * @param generateMipMaps defines if the engine should generate the mip levels
         * @param invertY defines if data must be stored with Y axis inverted
         * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
         * @param compression defines the compression used (null by default)
         * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
         * @returns the raw texture inside an InternalTexture
         */
        Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
            if (compression === void 0) { compression = null; }
            if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
            texture.baseWidth = width;
            texture.baseHeight = height;
            texture.width = width;
            texture.height = height;
            texture.format = format;
            texture.generateMipMaps = generateMipMaps;
            texture.samplingMode = samplingMode;
            texture.invertY = invertY;
            texture._compression = compression;
            texture.type = type;
            if (!this._doNotHandleContextLost) {
                texture._bufferView = data;
            }
            this.updateRawTexture(texture, data, format, invertY, compression, type);
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
            // Filters
            var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
            this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
            if (generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            this._internalTexturesCache.push(texture);
            return texture;
        };
        /** @hidden */
        Engine.prototype._unpackFlipY = function (value) {
            if (this._unpackFlipYCached !== value) {
                this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
                if (this.enableUnpackFlipYCached) {
                    this._unpackFlipYCached = value;
                }
            }
        };
        /** @hidden */
        Engine.prototype._getUnpackAlignement = function () {
            return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
        };
        /**
         * Creates a dynamic texture
         * @param width defines the width of the texture
         * @param height defines the height of the texture
         * @param generateMipMaps defines if the engine should generate the mip levels
         * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
         * @returns the dynamic texture inside an InternalTexture
         */
        Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
            texture.baseWidth = width;
            texture.baseHeight = height;
            if (generateMipMaps) {
                width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
                height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
            }
            //  this.resetTextureCache();
            texture.width = width;
            texture.height = height;
            texture.isReady = false;
            texture.generateMipMaps = generateMipMaps;
            texture.samplingMode = samplingMode;
            this.updateTextureSamplingMode(samplingMode, texture);
            this._internalTexturesCache.push(texture);
            return texture;
        };
        /**
         * Update the sampling mode of a given texture
         * @param samplingMode defines the required sampling mode
         * @param texture defines the texture to update
         */
        Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
            var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
            if (texture.isCube) {
                this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
                this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
            }
            else if (texture.is3D) {
                this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
                this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
                this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
            }
            else {
                this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
                this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
                this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            }
            texture.samplingMode = samplingMode;
        };
        /**
         * Update the content of a dynamic texture
         * @param texture defines the texture to update
         * @param canvas defines the canvas containing the source
         * @param invertY defines if data must be stored with Y axis inverted
         * @param premulAlpha defines if alpha is stored as premultiplied
         * @param format defines the format of the data
         */
        Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
            if (premulAlpha === void 0) { premulAlpha = false; }
            if (!texture) {
                return;
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
            this._unpackFlipY(invertY);
            if (premulAlpha) {
                this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
            }
            var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
            this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
            if (texture.generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            if (premulAlpha) {
                this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
            }
            texture.isReady = true;
        };
        /**
         * Update a video texture
         * @param texture defines the texture to update
         * @param video defines the video element to use
         * @param invertY defines if data must be stored with Y axis inverted
         */
        Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
            if (!texture || texture._isDisabled) {
                return;
            }
            var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
            this._unpackFlipY(!invertY); // Video are upside down by default
            try {
                // Testing video texture support
                if (this._videoTextureSupported === undefined) {
                    this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
                    if (this._gl.getError() !== 0) {
                        this._videoTextureSupported = false;
                    }
                    else {
                        this._videoTextureSupported = true;
                    }
                }
                // Copy video through the current working canvas if video texture is not supported
                if (!this._videoTextureSupported) {
                    if (!texture._workingCanvas) {
                        texture._workingCanvas = document.createElement("canvas");
                        var context = texture._workingCanvas.getContext("2d");
                        if (!context) {
                            throw new Error("Unable to get 2d context");
                        }
                        texture._workingContext = context;
                        texture._workingCanvas.width = texture.width;
                        texture._workingCanvas.height = texture.height;
                    }
                    texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
                    this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
                }
                else {
                    this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
                }
                if (texture.generateMipMaps) {
                    this._gl.generateMipmap(this._gl.TEXTURE_2D);
                }
                if (!wasPreviouslyBound) {
                    this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
                }
                //    this.resetTextureCache();
                texture.isReady = true;
            }
            catch (ex) {
                // Something unexpected
                // Let's disable the texture
                texture._isDisabled = true;
            }
        };
        /**
         * Updates a depth texture Comparison Mode and Function.
         * If the comparison Function is equal to 0, the mode will be set to none.
         * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
         * @param texture The texture to set the comparison function for
         * @param comparisonFunction The comparison function to set, 0 if no comparison required
         */
        Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
            if (this.webGLVersion === 1) {
                BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
                return;
            }
            var gl = this._gl;
            if (texture.isCube) {
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
                if (comparisonFunction === 0) {
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
                }
                else {
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
                }
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
            }
            else {
                this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
                if (comparisonFunction === 0) {
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
                }
                else {
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
                    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
                }
                this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
            }
            texture._comparisonFunction = comparisonFunction;
        };
        Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
            var width = size.width || size;
            var height = size.height || size;
            internalTexture.baseWidth = width;
            internalTexture.baseHeight = height;
            internalTexture.width = width;
            internalTexture.height = height;
            internalTexture.isReady = true;
            internalTexture.samples = 1;
            internalTexture.generateMipMaps = false;
            internalTexture._generateDepthBuffer = true;
            internalTexture._generateStencilBuffer = generateStencil;
            internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
            internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
            internalTexture._comparisonFunction = comparisonFunction;
            var gl = this._gl;
            var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
            var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
            gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
            gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
            gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            if (comparisonFunction === 0) {
                gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
                gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
            }
            else {
                gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
                gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
            }
        };
        /**
         * Creates a depth stencil texture.
         * This is only available in WebGL 2 or with the depth texture extension available.
         * @param size The size of face edge in the texture.
         * @param options The options defining the texture.
         * @returns The texture
         */
        Engine.prototype.createDepthStencilTexture = function (size, options) {
            if (options.isCube) {
                var width = size.width || size;
                return this._createDepthStencilCubeTexture(width, options);
            }
            else {
                return this._createDepthStencilTexture(size, options);
            }
        };
        /**
         * Creates a depth stencil texture.
         * This is only available in WebGL 2 or with the depth texture extension available.
         * @param size The size of face edge in the texture.
         * @param options The options defining the texture.
         * @returns The texture
         */
        Engine.prototype._createDepthStencilTexture = function (size, options) {
            var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
            if (!this._caps.depthTextureExtension) {
                BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
                return internalTexture;
            }
            var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
            var gl = this._gl;
            this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
            this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
            if (this.webGLVersion > 1) {
                if (internalOptions.generateStencil) {
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
                }
                else {
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
                }
            }
            else {
                if (internalOptions.generateStencil) {
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
                }
                else {
                    gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
                }
            }
            this._bindTextureDirectly(gl.TEXTURE_2D, null);
            return internalTexture;
        };
        /**
         * Creates a depth stencil cube texture.
         * This is only available in WebGL 2.
         * @param size The size of face edge in the cube texture.
         * @param options The options defining the cube texture.
         * @returns The cube texture
         */
        Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
            var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
            internalTexture.isCube = true;
            if (this.webGLVersion === 1) {
                BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
                return internalTexture;
            }
            var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
            var gl = this._gl;
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
            this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
            // Create the depth/stencil buffer
            for (var face = 0; face < 6; face++) {
                if (internalOptions.generateStencil) {
                    gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
                }
                else {
                    gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
                }
            }
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            return internalTexture;
        };
        /**
         * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
         * @param renderTarget The render target to set the frame buffer for
         */
        Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
            // Create the framebuffer
            var internalTexture = renderTarget.getInternalTexture();
            if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
                return;
            }
            var gl = this._gl;
            var depthStencilTexture = renderTarget.depthStencilTexture;
            this.bindUnboundFramebuffer(internalTexture._framebuffer);
            if (depthStencilTexture.isCube) {
                if (depthStencilTexture._generateStencilBuffer) {
                    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
                }
                else {
                    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
                }
            }
            else {
                if (depthStencilTexture._generateStencilBuffer) {
                    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
                }
                else {
                    gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
                }
            }
            this.bindUnboundFramebuffer(null);
        };
        /**
         * Creates a new render target texture
         * @param size defines the size of the texture
         * @param options defines the options used to create the texture
         * @returns a new render target texture stored in an InternalTexture
         */
        Engine.prototype.createRenderTargetTexture = function (size, options) {
            var fullOptions = new RenderTargetCreationOptions();
            if (options !== undefined && typeof options === "object") {
                fullOptions.generateMipMaps = options.generateMipMaps;
                fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
                fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
                fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
                fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
                fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
            }
            else {
                fullOptions.generateMipMaps = options;
                fullOptions.generateDepthBuffer = true;
                fullOptions.generateStencilBuffer = false;
                fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
                fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
                fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
            }
            if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
                // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
                fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
            }
            else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
                // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
                fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
            }
            var gl = this._gl;
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
            this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
            var width = size.width || size;
            var height = size.height || size;
            var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
            if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
                fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
                BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
            }
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
            // Create the framebuffer
            var currentFrameBuffer = this._currentFramebuffer;
            var framebuffer = gl.createFramebuffer();
            this.bindUnboundFramebuffer(framebuffer);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
            texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
            if (fullOptions.generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_2D);
            }
            // Unbind
            this._bindTextureDirectly(gl.TEXTURE_2D, null);
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            this.bindUnboundFramebuffer(currentFrameBuffer);
            texture._framebuffer = framebuffer;
            texture.baseWidth = width;
            texture.baseHeight = height;
            texture.width = width;
            texture.height = height;
            texture.isReady = true;
            texture.samples = 1;
            texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
            texture.samplingMode = fullOptions.samplingMode;
            texture.type = fullOptions.type;
            texture.format = fullOptions.format;
            texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
            texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
            // this.resetTextureCache();
            this._internalTexturesCache.push(texture);
            return texture;
        };
        /**
         * Create a multi render target texture
         * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
         * @param size defines the size of the texture
         * @param options defines the creation options
         * @returns the cube texture as an InternalTexture
         */
        Engine.prototype.createMultipleRenderTarget = function (size, options) {
            var generateMipMaps = false;
            var generateDepthBuffer = true;
            var generateStencilBuffer = false;
            var generateDepthTexture = false;
            var textureCount = 1;
            var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
            var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
            var types = new Array();
            var samplingModes = new Array();
            if (options !== undefined) {
                generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
                generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
                generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
                generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
                textureCount = options.textureCount || 1;
                if (options.types) {
                    types = options.types;
                }
                if (options.samplingModes) {
                    samplingModes = options.samplingModes;
                }
            }
            var gl = this._gl;
            // Create the framebuffer
            var framebuffer = gl.createFramebuffer();
            this.bindUnboundFramebuffer(framebuffer);
            var width = size.width || size;
            var height = size.height || size;
            var textures = [];
            var attachments = [];
            var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
            for (var i = 0; i < textureCount; i++) {
                var samplingMode = samplingModes[i] || defaultSamplingMode;
                var type = types[i] || defaultType;
                if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
                    // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
                    samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
                }
                else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
                    // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
                    samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
                }
                var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
                if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
                    type = Engine.TEXTURETYPE_UNSIGNED_INT;
                    BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
                }
                var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
                var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
                textures.push(texture);
                attachments.push(attachment);
                gl.activeTexture(gl["TEXTURE" + i]);
                gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
                gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
                if (generateMipMaps) {
                    this._gl.generateMipmap(this._gl.TEXTURE_2D);
                }
                // Unbind
                this._bindTextureDirectly(gl.TEXTURE_2D, null);
                texture._framebuffer = framebuffer;
                texture._depthStencilBuffer = depthStencilBuffer;
                texture.baseWidth = width;
                texture.baseHeight = height;
                texture.width = width;
                texture.height = height;
                texture.isReady = true;
                texture.samples = 1;
                texture.generateMipMaps = generateMipMaps;
                texture.samplingMode = samplingMode;
                texture.type = type;
                texture._generateDepthBuffer = generateDepthBuffer;
                texture._generateStencilBuffer = generateStencilBuffer;
                texture._attachments = attachments;
                this._internalTexturesCache.push(texture);
            }
            if (generateDepthTexture && this._caps.depthTextureExtension) {
                // Depth texture
                var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
                depthTexture._framebuffer = framebuffer;
                depthTexture.baseWidth = width;
                depthTexture.baseHeight = height;
                depthTexture.width = width;
                depthTexture.height = height;
                depthTexture.isReady = true;
                depthTexture.samples = 1;
                depthTexture.generateMipMaps = generateMipMaps;
                depthTexture.samplingMode = gl.NEAREST;
                depthTexture._generateDepthBuffer = generateDepthBuffer;
                depthTexture._generateStencilBuffer = generateStencilBuffer;
                textures.push(depthTexture);
                this._internalTexturesCache.push(depthTexture);
            }
            gl.drawBuffers(attachments);
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            this.bindUnboundFramebuffer(null);
            this.resetTextureCache();
            return textures;
        };
        Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
            if (samples === void 0) { samples = 1; }
            var depthStencilBuffer = null;
            var gl = this._gl;
            // Create the depth/stencil buffer
            if (generateStencilBuffer) {
                depthStencilBuffer = gl.createRenderbuffer();
                gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
                if (samples > 1) {
                    gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
                }
                else {
                    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
                }
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
            }
            else if (generateDepthBuffer) {
                depthStencilBuffer = gl.createRenderbuffer();
                gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
                if (samples > 1) {
                    gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
                }
                else {
                    gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
                }
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
            }
            return depthStencilBuffer;
        };
        /**
         * Updates the sample count of a render target texture
         * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
         * @param texture defines the texture to update
         * @param samples defines the sample count to set
         * @returns the effective sample count (could be 0 if multisample render targets are not supported)
         */
        Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
            if (this.webGLVersion < 2 || !texture) {
                return 1;
            }
            if (texture.samples === samples) {
                return samples;
            }
            var gl = this._gl;
            samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
            // Dispose previous render buffers
            if (texture._depthStencilBuffer) {
                gl.deleteRenderbuffer(texture._depthStencilBuffer);
                texture._depthStencilBuffer = null;
            }
            if (texture._MSAAFramebuffer) {
                gl.deleteFramebuffer(texture._MSAAFramebuffer);
                texture._MSAAFramebuffer = null;
            }
            if (texture._MSAARenderBuffer) {
                gl.deleteRenderbuffer(texture._MSAARenderBuffer);
                texture._MSAARenderBuffer = null;
            }
            if (samples > 1) {
                var framebuffer = gl.createFramebuffer();
                if (!framebuffer) {
                    throw new Error("Unable to create multi sampled framebuffer");
                }
                texture._MSAAFramebuffer = framebuffer;
                this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
                var colorRenderbuffer = gl.createRenderbuffer();
                if (!colorRenderbuffer) {
                    throw new Error("Unable to create multi sampled framebuffer");
                }
                gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
                gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
                texture._MSAARenderBuffer = colorRenderbuffer;
            }
            else {
                this.bindUnboundFramebuffer(texture._framebuffer);
            }
            texture.samples = samples;
            texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            this.bindUnboundFramebuffer(null);
            return samples;
        };
        /**
         * Update the sample count for a given multiple render target texture
         * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
         * @param textures defines the textures to update
         * @param samples defines the sample count to set
         * @returns the effective sample count (could be 0 if multisample render targets are not supported)
         */
        Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
            if (this.webGLVersion < 2 || !textures || textures.length == 0) {
                return 1;
            }
            if (textures[0].samples === samples) {
                return samples;
            }
            var gl = this._gl;
            samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
            // Dispose previous render buffers
            if (textures[0]._depthStencilBuffer) {
                gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
                textures[0]._depthStencilBuffer = null;
            }
            if (textures[0]._MSAAFramebuffer) {
                gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
                textures[0]._MSAAFramebuffer = null;
            }
            for (var i = 0; i < textures.length; i++) {
                if (textures[i]._MSAARenderBuffer) {
                    gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
                    textures[i]._MSAARenderBuffer = null;
                }
            }
            if (samples > 1) {
                var framebuffer = gl.createFramebuffer();
                if (!framebuffer) {
                    throw new Error("Unable to create multi sampled framebuffer");
                }
                this.bindUnboundFramebuffer(framebuffer);
                var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
                var attachments = [];
                for (var i = 0; i < textures.length; i++) {
                    var texture = textures[i];
                    var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
                    var colorRenderbuffer = gl.createRenderbuffer();
                    if (!colorRenderbuffer) {
                        throw new Error("Unable to create multi sampled framebuffer");
                    }
                    gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
                    gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
                    gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
                    texture._MSAAFramebuffer = framebuffer;
                    texture._MSAARenderBuffer = colorRenderbuffer;
                    texture.samples = samples;
                    texture._depthStencilBuffer = depthStencilBuffer;
                    gl.bindRenderbuffer(gl.RENDERBUFFER, null);
                    attachments.push(attachment);
                }
                gl.drawBuffers(attachments);
            }
            else {
                this.bindUnboundFramebuffer(textures[0]._framebuffer);
            }
            this.bindUnboundFramebuffer(null);
            return samples;
        };
        /** @hidden */
        Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
            var gl = this._gl;
            var target = gl.TEXTURE_2D;
            if (texture.isCube) {
                target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
            }
            this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
        };
        /** @hidden */
        Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
            var gl = this._gl;
            var textureType = this._getWebGLTextureType(texture.type);
            var format = this._getInternalFormat(texture.format);
            var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
            this._unpackFlipY(texture.invertY);
            var target = gl.TEXTURE_2D;
            if (texture.isCube) {
                target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
            }
            var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
            var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
            var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
            var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
            gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
        };
        /** @hidden */
        Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
            var gl = this._gl;
            var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
            this._bindTextureDirectly(bindTarget, texture, true);
            this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
            this._bindTextureDirectly(bindTarget, null, true);
        };
        /** @hidden */
        Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
            var gl = this._gl;
            var textureType = this._getWebGLTextureType(texture.type);
            var format = this._getInternalFormat(texture.format);
            var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
            var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
            this._bindTextureDirectly(bindTarget, texture, true);
            this._unpackFlipY(texture.invertY);
            var target = gl.TEXTURE_2D;
            if (texture.isCube) {
                target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
            }
            gl.texImage2D(target, lod, internalFormat, format, textureType, image);
            this._bindTextureDirectly(bindTarget, null, true);
        };
        /**
         * Creates a new render target cube texture
         * @param size defines the size of the texture
         * @param options defines the options used to create the texture
         * @returns a new render target cube texture stored in an InternalTexture
         */
        Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
            var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
            fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
            if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
                // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
                fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
            }
            else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
                // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
                fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
            }
            var gl = this._gl;
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
            var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
            if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
                fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
                BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
            }
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            for (var face = 0; face < 6; face++) {
                gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
            }
            // Create the framebuffer
            var framebuffer = gl.createFramebuffer();
            this.bindUnboundFramebuffer(framebuffer);
            texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
            // MipMaps
            if (fullOptions.generateMipMaps) {
                gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
            }
            // Unbind
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            this.bindUnboundFramebuffer(null);
            texture._framebuffer = framebuffer;
            texture.width = size;
            texture.height = size;
            texture.isReady = true;
            texture.isCube = true;
            texture.samples = 1;
            texture.generateMipMaps = fullOptions.generateMipMaps;
            texture.samplingMode = fullOptions.samplingMode;
            texture.type = fullOptions.type;
            texture.format = fullOptions.format;
            texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
            texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
            this._internalTexturesCache.push(texture);
            return texture;
        };
        /**
         * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
         * @param rootUrl defines the url where the file to load is located
         * @param scene defines the current scene
         * @param lodScale defines scale to apply to the mip map selection
         * @param lodOffset defines offset to apply to the mip map selection
         * @param onLoad defines an optional callback raised when the texture is loaded
         * @param onError defines an optional callback raised if there is an issue to load the texture
         * @param format defines the format of the data
         * @param forcedExtension defines the extension to use to pick the right loader
         * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
         * @returns the cube texture as an InternalTexture
         */
        Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
            var _this = this;
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (forcedExtension === void 0) { forcedExtension = null; }
            if (createPolynomials === void 0) { createPolynomials = true; }
            var callback = function (loadData) {
                if (!loadData) {
                    if (onLoad) {
                        onLoad(null);
                    }
                    return;
                }
                var texture = loadData.texture;
                if (!createPolynomials) {
                    texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
                }
                else if (loadData.info.sphericalPolynomial) {
                    texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
                }
                texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
                if (_this._caps.textureLOD) {
                    // Do not add extra process if texture lod is supported.
                    if (onLoad) {
                        onLoad(texture);
                    }
                    return;
                }
                var mipSlices = 3;
                var gl = _this._gl;
                var width = loadData.width;
                if (!width) {
                    return;
                }
                var textures = [];
                for (var i = 0; i < mipSlices; i++) {
                    //compute LOD from even spacing in smoothness (matching shader calculation)
                    var smoothness = i / (mipSlices - 1);
                    var roughness = 1 - smoothness;
                    var minLODIndex = lodOffset; // roughness = 0
                    var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
                    var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
                    var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
                    var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
                    glTextureFromLod.type = texture.type;
                    glTextureFromLod.format = texture.format;
                    glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
                    glTextureFromLod.height = glTextureFromLod.width;
                    glTextureFromLod.isCube = true;
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                    if (loadData.isDDS) {
                        var info = loadData.info;
                        var data = loadData.data;
                        _this._unpackFlipY(info.isCompressed);
                        BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
                    }
                    else {
                        BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
                    }
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
                    // Wrap in a base texture for easy binding.
                    var lodTexture = new BABYLON.BaseTexture(scene);
                    lodTexture.isCube = true;
                    lodTexture._texture = glTextureFromLod;
                    glTextureFromLod.isReady = true;
                    textures.push(lodTexture);
                }
                texture._lodTextureHigh = textures[2];
                texture._lodTextureMid = textures[1];
                texture._lodTextureLow = textures[0];
                if (onLoad) {
                    onLoad(texture);
                }
            };
            return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
        };
        /**
         * Creates a cube texture
         * @param rootUrl defines the url where the files to load is located
         * @param scene defines the current scene
         * @param files defines the list of files to load (1 per face)
         * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
         * @param onLoad defines an optional callback raised when the texture is loaded
         * @param onError defines an optional callback raised if there is an issue to load the texture
         * @param format defines the format of the data
         * @param forcedExtension defines the extension to use to pick the right loader
         * @param createPolynomials if a polynomial sphere should be created for the cube texture
         * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
         * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
         * @param fallback defines texture to use while falling back when (compressed) texture file not found.
         * @returns the cube texture as an InternalTexture
         */
        Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
            var _this = this;
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (forcedExtension === void 0) { forcedExtension = null; }
            if (createPolynomials === void 0) { createPolynomials = false; }
            if (lodScale === void 0) { lodScale = 0; }
            if (lodOffset === void 0) { lodOffset = 0; }
            if (fallback === void 0) { fallback = null; }
            var gl = this._gl;
            var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
            texture.isCube = true;
            texture.url = rootUrl;
            texture.generateMipMaps = !noMipmap;
            texture._lodGenerationScale = lodScale;
            texture._lodGenerationOffset = lodOffset;
            if (!this._doNotHandleContextLost) {
                texture._extension = forcedExtension;
                texture._files = files;
            }
            var lastDot = rootUrl.lastIndexOf('.');
            var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
            var loader = null;
            for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
                var availableLoader = _a[_i];
                if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
                    loader = availableLoader;
                    break;
                }
            }
            var onInternalError = function (request, exception) {
                if (loader) {
                    var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
                    if (fallbackUrl) {
                        _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
                    }
                }
                if (onError && request) {
                    onError(request.status + " " + request.statusText, exception);
                }
            };
            if (loader) {
                rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
                var onloaddata = function (data) {
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
                    loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
                };
                if (files && files.length === 6) {
                    if (loader.supportCascades) {
                        this._cascadeLoadFiles(scene, onloaddata, files, onError);
                    }
                    else if (onError) {
                        onError("Textures type does not support cascades.");
                    }
                }
                else {
                    this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
                }
            }
            else {
                if (!files) {
                    throw new Error("Cannot load cubemap because files were not defined");
                }
                this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
                    var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
                    var height = width;
                    _this._prepareWorkingCanvas();
                    if (!_this._workingCanvas || !_this._workingContext) {
                        return;
                    }
                    _this._workingCanvas.width = width;
                    _this._workingCanvas.height = height;
                    var faces = [
                        gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
                        gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
                    ];
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
                    _this._unpackFlipY(false);
                    var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
                    for (var index = 0; index < faces.length; index++) {
                        _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
                        gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
                    }
                    if (!noMipmap) {
                        gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
                    }
                    _this._setCubeMapTextureParams(!noMipmap);
                    texture.width = width;
                    texture.height = height;
                    texture.isReady = true;
                    if (format) {
                        texture.format = format;
                    }
                    texture.onLoadedObservable.notifyObservers(texture);
                    texture.onLoadedObservable.clear();
                    if (onLoad) {
                        onLoad();
                    }
                }, files, onError);
            }
            this._internalTexturesCache.push(texture);
            return texture;
        };
        /**
         * @hidden
         */
        Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
            var gl = this._gl;
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            //  this.resetTextureCache();
        };
        /**
         * Update a raw cube texture
         * @param texture defines the texture to udpdate
         * @param data defines the data to store
         * @param format defines the data format
         * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
         * @param invertY defines if data must be stored with Y axis inverted
         * @param compression defines the compression used (null by default)
         * @param level defines which level of the texture to update
         */
        Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
            if (compression === void 0) { compression = null; }
            if (level === void 0) { level = 0; }
            texture._bufferViewArray = data;
            texture.format = format;
            texture.type = type;
            texture.invertY = invertY;
            texture._compression = compression;
            var gl = this._gl;
            var textureType = this._getWebGLTextureType(type);
            var internalFormat = this._getInternalFormat(format);
            var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
            var needConversion = false;
            if (internalFormat === gl.RGB) {
                internalFormat = gl.RGBA;
                needConversion = true;
            }
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
            this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
            if (texture.width % 4 !== 0) {
                gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
            }
            // Data are known to be in +X +Y +Z -X -Y -Z
            for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                var faceData = data[faceIndex];
                if (compression) {
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
                }
                else {
                    if (needConversion) {
                        faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
                    }
                    gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
                }
            }
            var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
            if (isPot && texture.generateMipMaps && level === 0) {
                this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
            // this.resetTextureCache();
            texture.isReady = true;
        };
        /**
         * Creates a new raw cube texture
         * @param data defines the array of data to use to create each face
         * @param size defines the size of the textures
         * @param format defines the format of the data
         * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
         * @param generateMipMaps  defines if the engine should generate the mip levels
         * @param invertY defines if data must be stored with Y axis inverted
         * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
         * @param compression defines the compression used (null by default)
         * @returns the cube texture as an InternalTexture
         */
        Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
            if (compression === void 0) { compression = null; }
            var gl = this._gl;
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
            texture.isCube = true;
            texture.format = format;
            texture.type = type;
            if (!this._doNotHandleContextLost) {
                texture._bufferViewArray = data;
            }
            var textureType = this._getWebGLTextureType(type);
            var internalFormat = this._getInternalFormat(format);
            if (internalFormat === gl.RGB) {
                internalFormat = gl.RGBA;
            }
            // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
            if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
                generateMipMaps = false;
                samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
                BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
            }
            else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
                generateMipMaps = false;
                samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
                BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
            }
            else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
                generateMipMaps = false;
                BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
            }
            else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
                generateMipMaps = false;
                BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
            }
            var width = size;
            var height = width;
            texture.width = width;
            texture.height = height;
            // Double check on POT to generate Mips.
            var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
            if (!isPot) {
                generateMipMaps = false;
            }
            // Upload data if needed. The texture won't be ready until then.
            if (data) {
                this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
            // Filters
            if (data && generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
            }
            var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
            this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
            texture.generateMipMaps = generateMipMaps;
            return texture;
        };
        /**
         * Creates a new raw cube texture from a specified url
         * @param url defines the url where the data is located
         * @param scene defines the current scene
         * @param size defines the size of the textures
         * @param format defines the format of the data
         * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
         * @param noMipmap defines if the engine should avoid generating the mip levels
         * @param callback defines a callback used to extract texture data from loaded data
         * @param mipmapGenerator defines to provide an optional tool to generate mip levels
         * @param onLoad defines a callback called when texture is loaded
         * @param onError defines a callback called if there is an error
         * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
         * @param invertY defines if data must be stored with Y axis inverted
         * @returns the cube texture as an InternalTexture
         */
        Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
            var _this = this;
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
            if (invertY === void 0) { invertY = false; }
            var gl = this._gl;
            var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
            scene._addPendingData(texture);
            texture.url = url;
            this._internalTexturesCache.push(texture);
            var onerror = function (request, exception) {
                scene._removePendingData(texture);
                if (onError && request) {
                    onError(request.status + " " + request.statusText, exception);
                }
            };
            var internalCallback = function (data) {
                var width = texture.width;
                var faceDataArrays = callback(data);
                if (!faceDataArrays) {
                    return;
                }
                if (mipmapGenerator) {
                    var textureType = _this._getWebGLTextureType(type);
                    var internalFormat = _this._getInternalFormat(format);
                    var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
                    var needConversion = false;
                    if (internalFormat === gl.RGB) {
                        internalFormat = gl.RGBA;
                        needConversion = true;
                    }
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
                    _this._unpackFlipY(false);
                    var mipData = mipmapGenerator(faceDataArrays);
                    for (var level = 0; level < mipData.length; level++) {
                        var mipSize = width >> level;
                        for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                            var mipFaceData = mipData[level][faceIndex];
                            if (needConversion) {
                                mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
                            }
                            gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
                        }
                    }
                    _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
                }
                else {
                    _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
                }
                texture.isReady = true;
                // this.resetTextureCache();
                scene._removePendingData(texture);
                if (onLoad) {
                    onLoad();
                }
            };
            this._loadFile(url, function (data) {
                internalCallback(data);
            }, undefined, scene.database, true, onerror);
            return texture;
        };
        /**
         * Update a raw 3D texture
         * @param texture defines the texture to update
         * @param data defines the data to store
         * @param format defines the data format
         * @param invertY defines if data must be stored with Y axis inverted
         * @param compression defines the used compression (can be null)
         * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
         */
        Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
            if (compression === void 0) { compression = null; }
            if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
            var internalType = this._getWebGLTextureType(textureType);
            var internalFormat = this._getInternalFormat(format);
            var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
            this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
            this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
            if (!this._doNotHandleContextLost) {
                texture._bufferView = data;
                texture.format = format;
                texture.invertY = invertY;
                texture._compression = compression;
            }
            if (texture.width % 4 !== 0) {
                this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
            }
            if (compression && data) {
                this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
            }
            else {
                this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
            }
            if (texture.generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_3D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
            // this.resetTextureCache();
            texture.isReady = true;
        };
        /**
         * Creates a new raw 3D texture
         * @param data defines the data used to create the texture
         * @param width defines the width of the texture
         * @param height defines the height of the texture
         * @param depth defines the depth of the texture
         * @param format defines the format of the texture
         * @param generateMipMaps defines if the engine must generate mip levels
         * @param invertY defines if data must be stored with Y axis inverted
         * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
         * @param compression defines the compressed used (can be null)
         * @param textureType defines the compressed used (can be null)
         * @returns a new raw 3D texture (stored in an InternalTexture)
         */
        Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
            if (compression === void 0) { compression = null; }
            if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
            texture.baseWidth = width;
            texture.baseHeight = height;
            texture.baseDepth = depth;
            texture.width = width;
            texture.height = height;
            texture.depth = depth;
            texture.format = format;
            texture.type = textureType;
            texture.generateMipMaps = generateMipMaps;
            texture.samplingMode = samplingMode;
            texture.is3D = true;
            if (!this._doNotHandleContextLost) {
                texture._bufferView = data;
            }
            this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
            this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
            // Filters
            var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
            this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
            this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
            if (generateMipMaps) {
                this._gl.generateMipmap(this._gl.TEXTURE_3D);
            }
            this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
            this._internalTexturesCache.push(texture);
            return texture;
        };
        Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
            var gl = this._gl;
            if (!gl) {
                return;
            }
            var filters = this._getSamplingParameters(samplingMode, !noMipmap);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
            if (!noMipmap && !isCompressed) {
                gl.generateMipmap(gl.TEXTURE_2D);
            }
            this._bindTextureDirectly(gl.TEXTURE_2D, null);
            // this.resetTextureCache();
            if (scene) {
                scene._removePendingData(texture);
            }
            texture.onLoadedObservable.notifyObservers(texture);
            texture.onLoadedObservable.clear();
        };
        Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
            var _this = this;
            if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
            var maxTextureSize = this.getCaps().maxTextureSize;
            var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
            var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
            var gl = this._gl;
            if (!gl) {
                return;
            }
            if (!texture._webGLTexture) {
                //  this.resetTextureCache();
                if (scene) {
                    scene._removePendingData(texture);
                }
                return;
            }
            this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
            this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
            texture.baseWidth = width;
            texture.baseHeight = height;
            texture.width = potWidth;
            texture.height = potHeight;
            texture.isReady = true;
            if (processFunction(potWidth, potHeight, function () {
                _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
            })) {
                // Returning as texture needs extra async steps
                return;
            }
            this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
        };
        Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
            // Create new RGBA data container.
            var rgbaData;
            if (textureType === Engine.TEXTURETYPE_FLOAT) {
                rgbaData = new Float32Array(width * height * 4);
            }
            else {
                rgbaData = new Uint32Array(width * height * 4);
            }
            // Convert each pixel.
            for (var x = 0; x < width; x++) {
                for (var y = 0; y < height; y++) {
                    var index = (y * width + x) * 3;
                    var newIndex = (y * width + x) * 4;
                    // Map Old Value to new value.
                    rgbaData[newIndex + 0] = rgbData[index + 0];
                    rgbaData[newIndex + 1] = rgbData[index + 1];
                    rgbaData[newIndex + 2] = rgbData[index + 2];
                    // Add fully opaque alpha channel.
                    rgbaData[newIndex + 3] = 1;
                }
            }
            return rgbaData;
        };
        /** @hidden */
        Engine.prototype._releaseFramebufferObjects = function (texture) {
            var gl = this._gl;
            if (texture._framebuffer) {
                gl.deleteFramebuffer(texture._framebuffer);
                texture._framebuffer = null;
            }
            if (texture._depthStencilBuffer) {
                gl.deleteRenderbuffer(texture._depthStencilBuffer);
                texture._depthStencilBuffer = null;
            }
            if (texture._MSAAFramebuffer) {
                gl.deleteFramebuffer(texture._MSAAFramebuffer);
                texture._MSAAFramebuffer = null;
            }
            if (texture._MSAARenderBuffer) {
                gl.deleteRenderbuffer(texture._MSAARenderBuffer);
                texture._MSAARenderBuffer = null;
            }
        };
        /** @hidden */
        Engine.prototype._releaseTexture = function (texture) {
            var gl = this._gl;
            this._releaseFramebufferObjects(texture);
            gl.deleteTexture(texture._webGLTexture);
            // Unbind channels
            this.unbindAllTextures();
            var index = this._internalTexturesCache.indexOf(texture);
            if (index !== -1) {
                this._internalTexturesCache.splice(index, 1);
            }
            // Integrated fixed lod samplers.
            if (texture._lodTextureHigh) {
                texture._lodTextureHigh.dispose();
            }
            if (texture._lodTextureMid) {
                texture._lodTextureMid.dispose();
            }
            if (texture._lodTextureLow) {
                texture._lodTextureLow.dispose();
            }
            // Set output texture of post process to null if the texture has been released/disposed
            this.scenes.forEach(function (scene) {
                scene.postProcesses.forEach(function (postProcess) {
                    if (postProcess._outputTexture == texture) {
                        postProcess._outputTexture = null;
                    }
                });
                scene.cameras.forEach(function (camera) {
                    camera._postProcesses.forEach(function (postProcess) {
                        if (postProcess) {
                            if (postProcess._outputTexture == texture) {
                                postProcess._outputTexture = null;
                            }
                        }
                    });
                });
            });
        };
        Engine.prototype.setProgram = function (program) {
            if (this._currentProgram !== program) {
                this._gl.useProgram(program);
                this._currentProgram = program;
            }
        };
        /**
         * Binds an effect to the webGL context
         * @param effect defines the effect to bind
         */
        Engine.prototype.bindSamplers = function (effect) {
            this.setProgram(effect.getProgram());
            var samplers = effect.getSamplers();
            for (var index = 0; index < samplers.length; index++) {
                var uniform = effect.getUniform(samplers[index]);
                if (uniform) {
                    this._boundUniforms[index] = uniform;
                }
            }
            this._currentEffect = null;
        };
        Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
            if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
                return;
            }
            // Remove
            this._linkTrackers(internalTexture.previous, internalTexture.next);
            // Bind last to it
            this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
            // Bind to dummy
            this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
        };
        Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
            if (!internalTexture) {
                return -1;
            }
            internalTexture._initialSlot = channel;
            if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
                if (channel !== internalTexture._designatedSlot) {
                    this._textureCollisions.addCount(1, false);
                }
            }
            else {
                if (channel !== internalTexture._designatedSlot) {
                    if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
                        return internalTexture._designatedSlot;
                    }
                    else {
                        // No slot for this texture, let's pick a new one (if we find a free slot)
                        if (this._nextFreeTextureSlots.length) {
                            return this._nextFreeTextureSlots[0];
                        }
                        // We need to recycle the oldest bound texture, sorry.
                        this._textureCollisions.addCount(1, false);
                        return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
                    }
                }
            }
            return channel;
        };
        Engine.prototype._linkTrackers = function (previous, next) {
            previous.next = next;
            next.previous = previous;
        };
        Engine.prototype._removeDesignatedSlot = function (internalTexture) {
            var currentSlot = internalTexture._designatedSlot;
            if (currentSlot === -1) {
                return -1;
            }
            internalTexture._designatedSlot = -1;
            if (this.disableTextureBindingOptimization) {
                return -1;
            }
            // Remove from bound list
            this._linkTrackers(internalTexture.previous, internalTexture.next);
            // Free the slot
            this._boundTexturesCache[currentSlot] = null;
            this._nextFreeTextureSlots.push(currentSlot);
            return currentSlot;
        };
        Engine.prototype._activateCurrentTexture = function () {
            if (this._currentTextureChannel !== this._activeChannel) {
                this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
                this._currentTextureChannel = this._activeChannel;
            }
        };
        /** @hidden */
        Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
            if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
            if (force === void 0) { force = false; }
            var wasPreviouslyBound = false;
            if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
                this._activeChannel = texture._designatedSlot;
            }
            var currentTextureBound = this._boundTexturesCache[this._activeChannel];
            var isTextureForRendering = texture && texture._initialSlot > -1;
            if (currentTextureBound !== texture || force) {
                if (currentTextureBound) {
                    this._removeDesignatedSlot(currentTextureBound);
                }
                this._activateCurrentTexture();
                this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
                this._boundTexturesCache[this._activeChannel] = texture;
                if (texture) {
                    if (!this.disableTextureBindingOptimization) {
                        var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
                        if (slotIndex > -1) {
                            this._nextFreeTextureSlots.splice(slotIndex, 1);
                        }
                        this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
                        this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
                    }
                    texture._designatedSlot = this._activeChannel;
                }
            }
            else if (forTextureDataUpdate) {
                wasPreviouslyBound = true;
                this._activateCurrentTexture();
            }
            if (isTextureForRendering && !forTextureDataUpdate) {
                this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
            }
            return wasPreviouslyBound;
        };
        /** @hidden */
        Engine.prototype._bindTexture = function (channel, texture) {
            if (channel < 0) {
                return;
            }
            if (texture) {
                channel = this._getCorrectTextureChannel(channel, texture);
            }
            this._activeChannel = channel;
            this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
        };
        /**
         * Sets a texture to the webGL context from a postprocess
         * @param channel defines the channel to use
         * @param postProcess defines the source postprocess
         */
        Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
            this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
        };
        /**
         * Binds the output of the passed in post process to the texture channel specified
         * @param channel The channel the texture should be bound to
         * @param postProcess The post process which's output should be bound
         */
        Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
            this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
        };
        /**
         * Unbind all textures from the webGL context
         */
        Engine.prototype.unbindAllTextures = function () {
            for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
                this._activeChannel = channel;
                this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
                this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
                if (this.webGLVersion > 1) {
                    this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
                }
            }
        };
        /**
         * Sets a texture to the according uniform.
         * @param channel The texture channel
         * @param uniform The uniform to set
         * @param texture The texture to apply
         */
        Engine.prototype.setTexture = function (channel, uniform, texture) {
            if (channel < 0) {
                return;
            }
            if (uniform) {
                this._boundUniforms[channel] = uniform;
            }
            this._setTexture(channel, texture);
        };
        /**
         * Sets a depth stencil texture from a render target to the according uniform.
         * @param channel The texture channel
         * @param uniform The uniform to set
         * @param texture The render target texture containing the depth stencil texture to apply
         */
        Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
            if (channel < 0) {
                return;
            }
            if (uniform) {
                this._boundUniforms[channel] = uniform;
            }
            if (!texture || !texture.depthStencilTexture) {
                this._setTexture(channel, null);
            }
            else {
                this._setTexture(channel, texture, false, true);
            }
        };
        Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
            var uniform = this._boundUniforms[sourceSlot];
            if (uniform._currentState === destination) {
                return;
            }
            this._gl.uniform1i(uniform, destination);
            uniform._currentState = destination;
        };
        Engine.prototype._getTextureWrapMode = function (mode) {
            switch (mode) {
                case Engine.TEXTURE_WRAP_ADDRESSMODE:
                    return this._gl.REPEAT;
                case Engine.TEXTURE_CLAMP_ADDRESSMODE:
                    return this._gl.CLAMP_TO_EDGE;
                case Engine.TEXTURE_MIRROR_ADDRESSMODE:
                    return this._gl.MIRRORED_REPEAT;
            }
            return this._gl.REPEAT;
        };
        Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
            if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
            if (depthStencilTexture === void 0) { depthStencilTexture = false; }
            // Not ready?
            if (!texture) {
                if (this._boundTexturesCache[channel] != null) {
                    this._activeChannel = channel;
                    this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
                    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
                    if (this.webGLVersion > 1) {
                        this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
                    }
                }
                return false;
            }
            // Video
            if (texture.video) {
                this._activeChannel = channel;
                texture.update();
            }
            else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
                texture.delayLoad();
                return false;
            }
            var internalTexture;
            if (depthStencilTexture) {
                internalTexture = texture.depthStencilTexture;
            }
            else if (texture.isReady()) {
                internalTexture = texture.getInternalTexture();
            }
            else if (texture.isCube) {
                internalTexture = this.emptyCubeTexture;
            }
            else if (texture.is3D) {
                internalTexture = this.emptyTexture3D;
            }
            else {
                internalTexture = this.emptyTexture;
            }
            if (!isPartOfTextureArray) {
                channel = this._getCorrectTextureChannel(channel, internalTexture);
            }
            var needToBind = true;
            if (this._boundTexturesCache[channel] === internalTexture) {
                this._moveBoundTextureOnTop(internalTexture);
                if (!isPartOfTextureArray) {
                    this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
                }
                needToBind = false;
            }
            this._activeChannel = channel;
            if (internalTexture && internalTexture.is3D) {
                if (needToBind) {
                    this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
                }
                if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
                    internalTexture._cachedWrapU = texture.wrapU;
                    this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
                }
                if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
                    internalTexture._cachedWrapV = texture.wrapV;
                    this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
                }
                if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
                    internalTexture._cachedWrapR = texture.wrapR;
                    this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
                }
                this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
            }
            else if (internalTexture && internalTexture.isCube) {
                if (needToBind) {
                    this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
                }
                if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
                    internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
                    // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE.  All other modes use REPEAT.
                    var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
                    this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
                    this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
                }
                this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
            }
            else {
                if (needToBind) {
                    this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
                }
                if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
                    internalTexture._cachedWrapU = texture.wrapU;
                    this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
                }
                if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
                    internalTexture._cachedWrapV = texture.wrapV;
                    this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
                }
                this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
            }
            return true;
        };
        /**
         * Sets an array of texture to the webGL context
         * @param channel defines the channel where the texture array must be set
         * @param uniform defines the associated uniform location
         * @param textures defines the array of textures to bind
         */
        Engine.prototype.setTextureArray = function (channel, uniform, textures) {
            if (channel < 0 || !uniform) {
                return;
            }
            if (!this._textureUnits || this._textureUnits.length !== textures.length) {
                this._textureUnits = new Int32Array(textures.length);
            }
            for (var i = 0; i < textures.length; i++) {
                this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
            }
            this._gl.uniform1iv(uniform, this._textureUnits);
            for (var index = 0; index < textures.length; index++) {
                this._setTexture(this._textureUnits[index], textures[index], true);
            }
        };
        /** @hidden */
        Engine.prototype._setAnisotropicLevel = function (target, texture) {
            var internalTexture = texture.getInternalTexture();
            if (!internalTexture) {
                return;
            }
            var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
            var value = texture.anisotropicFilteringLevel;
            if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
                && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
                && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
                value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
            }
            if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
                this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
                internalTexture._cachedAnisotropicFilteringLevel = value;
            }
        };
        Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
            this._bindTextureDirectly(target, texture, true, true);
            this._gl.texParameterf(target, parameter, value);
        };
        Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
            if (texture) {
                this._bindTextureDirectly(target, texture, true, true);
            }
            this._gl.texParameteri(target, parameter, value);
        };
        /**
         * Reads pixels from the current frame buffer. Please note that this function can be slow
         * @param x defines the x coordinate of the rectangle where pixels must be read
         * @param y defines the y coordinate of the rectangle where pixels must be read
         * @param width defines the width of the rectangle where pixels must be read
         * @param height defines the height of the rectangle where pixels must be read
         * @returns a Uint8Array containing RGBA colors
         */
        Engine.prototype.readPixels = function (x, y, width, height) {
            var data = new Uint8Array(height * width * 4);
            this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
            return data;
        };
        /**
         * Add an externaly attached data from its key.
         * This method call will fail and return false, if such key already exists.
         * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
         * @param key the unique key that identifies the data
         * @param data the data object to associate to the key for this Engine instance
         * @return true if no such key were already present and the data was added successfully, false otherwise
         */
        Engine.prototype.addExternalData = function (key, data) {
            if (!this._externalData) {
                this._externalData = new BABYLON.StringDictionary();
            }
            return this._externalData.add(key, data);
        };
        /**
         * Get an externaly attached data from its key
         * @param key the unique key that identifies the data
         * @return the associated data, if present (can be null), or undefined if not present
         */
        Engine.prototype.getExternalData = function (key) {
            if (!this._externalData) {
                this._externalData = new BABYLON.StringDictionary();
            }
            return this._externalData.get(key);
        };
        /**
         * Get an externaly attached data from its key, create it using a factory if it's not already present
         * @param key the unique key that identifies the data
         * @param factory the factory that will be called to create the instance if and only if it doesn't exists
         * @return the associated data, can be null if the factory returned null.
         */
        Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
            if (!this._externalData) {
                this._externalData = new BABYLON.StringDictionary();
            }
            return this._externalData.getOrAddWithFactory(key, factory);
        };
        /**
         * Remove an externaly attached data from the Engine instance
         * @param key the unique key that identifies the data
         * @return true if the data was successfully removed, false if it doesn't exist
         */
        Engine.prototype.removeExternalData = function (key) {
            if (!this._externalData) {
                this._externalData = new BABYLON.StringDictionary();
            }
            return this._externalData.remove(key);
        };
        /**
         * Unbind all vertex attributes from the webGL context
         */
        Engine.prototype.unbindAllAttributes = function () {
            if (this._mustWipeVertexAttributes) {
                this._mustWipeVertexAttributes = false;
                for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
                    this._gl.disableVertexAttribArray(i);
                    this._vertexAttribArraysEnabled[i] = false;
                    this._currentBufferPointers[i].active = false;
                }
                return;
            }
            for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
                if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
                    continue;
                }
                this._gl.disableVertexAttribArray(i);
                this._vertexAttribArraysEnabled[i] = false;
                this._currentBufferPointers[i].active = false;
            }
        };
        /**
         * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
         */
        Engine.prototype.releaseEffects = function () {
            for (var name in this._compiledEffects) {
                this._deleteProgram(this._compiledEffects[name]._program);
            }
            this._compiledEffects = {};
        };
        /**
         * Dispose and release all associated resources
         */
        Engine.prototype.dispose = function () {
            this.hideLoadingUI();
            this.stopRenderLoop();
            // Release postProcesses
            while (this.postProcesses.length) {
                this.postProcesses[0].dispose();
            }
            // Empty texture
            if (this._emptyTexture) {
                this._releaseTexture(this._emptyTexture);
                this._emptyTexture = null;
            }
            if (this._emptyCubeTexture) {
                this._releaseTexture(this._emptyCubeTexture);
                this._emptyCubeTexture = null;
            }
            // Rescale PP
            if (this._rescalePostProcess) {
                this._rescalePostProcess.dispose();
            }
            // Release scenes
            while (this.scenes.length) {
                this.scenes[0].dispose();
            }
            // Release audio engine
            if (Engine.Instances.length === 1 && Engine.audioEngine) {
                Engine.audioEngine.dispose();
            }
            // Release effects
            this.releaseEffects();
            // Unbind
            this.unbindAllAttributes();
            this._boundUniforms = [];
            if (this._dummyFramebuffer) {
                this._gl.deleteFramebuffer(this._dummyFramebuffer);
            }
            //WebVR
            this.disableVR();
            // Events
            if (BABYLON.Tools.IsWindowObjectExist()) {
                window.removeEventListener("blur", this._onBlur);
                window.removeEventListener("focus", this._onFocus);
                window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
                window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
                if (this._renderingCanvas) {
                    this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
                    this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
                    this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
                    if (!this._doNotHandleContextLost) {
                        this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
                        this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
                    }
                }
                document.removeEventListener("fullscreenchange", this._onFullscreenChange);
                document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
                document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
                document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
                document.removeEventListener("pointerlockchange", this._onPointerLockChange);
                document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
                document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
                document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
                if (this._onVrDisplayConnect) {
                    window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
                    if (this._onVrDisplayDisconnect) {
                        window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
                    }
                    if (this._onVrDisplayPresentChange) {
                        window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
                    }
                    this._onVrDisplayConnect = null;
                    this._onVrDisplayDisconnect = null;
                }
            }
            // Remove from Instances
            var index = Engine.Instances.indexOf(this);
            if (index >= 0) {
                Engine.Instances.splice(index, 1);
            }
            this._workingCanvas = null;
            this._workingContext = null;
            this._currentBufferPointers = [];
            this._renderingCanvas = null;
            this._currentProgram = null;
            this._bindedRenderFunction = null;
            this.onResizeObservable.clear();
            this.onCanvasBlurObservable.clear();
            this.onCanvasFocusObservable.clear();
            this.onCanvasPointerOutObservable.clear();
            this.onBeginFrameObservable.clear();
            this.onEndFrameObservable.clear();
            BABYLON.Effect.ResetCache();
            // Abort active requests
            for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
                var request = _a[_i];
                request.abort();
            }
        };
        // Loading screen
        /**
         * Display the loading screen
         * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
         */
        Engine.prototype.displayLoadingUI = function () {
            if (!BABYLON.Tools.IsWindowObjectExist()) {
                return;
            }
            var loadingScreen = this.loadingScreen;
            if (loadingScreen) {
                loadingScreen.displayLoadingUI();
            }
        };
        /**
         * Hide the loading screen
         * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
         */
        Engine.prototype.hideLoadingUI = function () {
            if (!BABYLON.Tools.IsWindowObjectExist()) {
                return;
            }
            var loadingScreen = this.loadingScreen;
            if (loadingScreen) {
                loadingScreen.hideLoadingUI();
            }
        };
        Object.defineProperty(Engine.prototype, "loadingScreen", {
            /**
             * Gets the current loading screen object
             * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
             */
            get: function () {
                if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas) {
                    this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
                }
                return this._loadingScreen;
            },
            /**
             * Sets the current loading screen object
             * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
             */
            set: function (loadingScreen) {
                this._loadingScreen = loadingScreen;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "loadingUIText", {
            /**
             * Sets the current loading screen text
             * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
             */
            set: function (text) {
                this.loadingScreen.loadingUIText = text;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
            /**
             * Sets the current loading screen background color
             * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
             */
            set: function (color) {
                this.loadingScreen.loadingUIBackgroundColor = color;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attach a new callback raised when context lost event is fired
         * @param callback defines the callback to call
         */
        Engine.prototype.attachContextLostEvent = function (callback) {
            if (this._renderingCanvas) {
                this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
            }
        };
        /**
         * Attach a new callback raised when context restored event is fired
         * @param callback defines the callback to call
         */
        Engine.prototype.attachContextRestoredEvent = function (callback) {
            if (this._renderingCanvas) {
                this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
            }
        };
        /**
         * Gets the source code of the vertex shader associated with a specific webGL program
         * @param program defines the program to use
         * @returns a string containing the source code of the vertex shader associated with the program
         */
        Engine.prototype.getVertexShaderSource = function (program) {
            var shaders = this._gl.getAttachedShaders(program);
            if (!shaders) {
                return null;
            }
            return this._gl.getShaderSource(shaders[0]);
        };
        /**
         * Gets the source code of the fragment shader associated with a specific webGL program
         * @param program defines the program to use
         * @returns a string containing the source code of the fragment shader associated with the program
         */
        Engine.prototype.getFragmentShaderSource = function (program) {
            var shaders = this._gl.getAttachedShaders(program);
            if (!shaders) {
                return null;
            }
            return this._gl.getShaderSource(shaders[1]);
        };
        /**
         * Get the current error code of the webGL context
         * @returns the error code
         * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
         */
        Engine.prototype.getError = function () {
            return this._gl.getError();
        };
        // FPS
        /**
         * Gets the current framerate
         * @returns a number representing the framerate
         */
        Engine.prototype.getFps = function () {
            return this._fps;
        };
        /**
         * Gets the time spent between current and previous frame
         * @returns a number representing the delta time in ms
         */
        Engine.prototype.getDeltaTime = function () {
            return this._deltaTime;
        };
        Engine.prototype._measureFps = function () {
            this._performanceMonitor.sampleFrame();
            this._fps = this._performanceMonitor.averageFPS;
            this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
        };
        /** @hidden */
        Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
            if (faceIndex === void 0) { faceIndex = -1; }
            if (level === void 0) { level = 0; }
            if (buffer === void 0) { buffer = null; }
            var gl = this._gl;
            if (!this._dummyFramebuffer) {
                var dummy = gl.createFramebuffer();
                if (!dummy) {
                    throw new Error("Unable to create dummy framebuffer");
                }
                this._dummyFramebuffer = dummy;
            }
            gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
            if (faceIndex > -1) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
            }
            else {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
            }
            var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
            switch (readType) {
                case gl.UNSIGNED_BYTE:
                    if (!buffer) {
                        buffer = new Uint8Array(4 * width * height);
                    }
                    readType = gl.UNSIGNED_BYTE;
                    break;
                default:
                    if (!buffer) {
                        buffer = new Float32Array(4 * width * height);
                    }
                    readType = gl.FLOAT;
                    break;
            }
            gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
            gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
            return buffer;
        };
        Engine.prototype._canRenderToFloatFramebuffer = function () {
            if (this._webGLVersion > 1) {
                return this._caps.colorBufferFloat;
            }
            return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
        };
        Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
            if (this._webGLVersion > 1) {
                return this._caps.colorBufferFloat;
            }
            return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
        };
        // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
        Engine.prototype._canRenderToFramebuffer = function (type) {
            var gl = this._gl;
            //clear existing errors
            while (gl.getError() !== gl.NO_ERROR) { }
            var successful = true;
            var texture = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, texture);
            gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
            var fb = gl.createFramebuffer();
            gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
            var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
            successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
            successful = successful && (gl.getError() === gl.NO_ERROR);
            //try render by clearing frame buffer's color buffer
            if (successful) {
                gl.clear(gl.COLOR_BUFFER_BIT);
                successful = successful && (gl.getError() === gl.NO_ERROR);
            }
            //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
            if (successful) {
                //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
                gl.bindFramebuffer(gl.FRAMEBUFFER, null);
                var readFormat = gl.RGBA;
                var readType = gl.UNSIGNED_BYTE;
                var buffer = new Uint8Array(4);
                gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
                successful = successful && (gl.getError() === gl.NO_ERROR);
            }
            //clean up
            gl.deleteTexture(texture);
            gl.deleteFramebuffer(fb);
            gl.bindFramebuffer(gl.FRAMEBUFFER, null);
            //clear accumulated errors
            while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
            return successful;
        };
        /** @hidden */
        Engine.prototype._getWebGLTextureType = function (type) {
            if (this._webGLVersion === 1) {
                switch (type) {
                    case Engine.TEXTURETYPE_FLOAT:
                        return this._gl.FLOAT;
                    case Engine.TEXTURETYPE_HALF_FLOAT:
                        return this._gl.HALF_FLOAT_OES;
                    case Engine.TEXTURETYPE_UNSIGNED_BYTE:
                        return this._gl.UNSIGNED_BYTE;
                }
                return this._gl.UNSIGNED_BYTE;
            }
            switch (type) {
                case Engine.TEXTURETYPE_BYTE:
                    return this._gl.BYTE;
                case Engine.TEXTURETYPE_UNSIGNED_BYTE:
                    return this._gl.UNSIGNED_BYTE;
                case Engine.TEXTURETYPE_SHORT:
                    return this._gl.SHORT;
                case Engine.TEXTURETYPE_UNSIGNED_SHORT:
                    return this._gl.UNSIGNED_SHORT;
                case Engine.TEXTURETYPE_INT:
                    return this._gl.INT;
                case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
                    return this._gl.UNSIGNED_INT;
                case Engine.TEXTURETYPE_FLOAT:
                    return this._gl.FLOAT;
                case Engine.TEXTURETYPE_HALF_FLOAT:
                    return this._gl.HALF_FLOAT;
                case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
                    return this._gl.UNSIGNED_SHORT_4_4_4_4;
                case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
                    return this._gl.UNSIGNED_SHORT_5_5_5_1;
                case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
                    return this._gl.UNSIGNED_SHORT_5_6_5;
                case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
                    return this._gl.UNSIGNED_INT_2_10_10_10_REV;
                case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
                    return this._gl.UNSIGNED_INT_24_8;
                case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
                    return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
                case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
                    return this._gl.UNSIGNED_INT_5_9_9_9_REV;
                case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
                    return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
            }
            return this._gl.UNSIGNED_BYTE;
        };
        Engine.prototype._getInternalFormat = function (format) {
            var internalFormat = this._gl.RGBA;
            switch (format) {
                case Engine.TEXTUREFORMAT_ALPHA:
                    internalFormat = this._gl.ALPHA;
                    break;
                case Engine.TEXTUREFORMAT_LUMINANCE:
                    internalFormat = this._gl.LUMINANCE;
                    break;
                case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
                    internalFormat = this._gl.LUMINANCE_ALPHA;
                    break;
                case Engine.TEXTUREFORMAT_RED:
                    internalFormat = this._gl.RED;
                    break;
                case Engine.TEXTUREFORMAT_RG:
                    internalFormat = this._gl.RG;
                    break;
                case Engine.TEXTUREFORMAT_RGB:
                    internalFormat = this._gl.RGB;
                    break;
                case Engine.TEXTUREFORMAT_RGBA:
                    internalFormat = this._gl.RGBA;
                    break;
            }
            if (this._webGLVersion > 1) {
                switch (format) {
                    case Engine.TEXTUREFORMAT_RED_INTEGER:
                        internalFormat = this._gl.RED_INTEGER;
                        break;
                    case Engine.TEXTUREFORMAT_RG_INTEGER:
                        internalFormat = this._gl.RG_INTEGER;
                        break;
                    case Engine.TEXTUREFORMAT_RGB_INTEGER:
                        internalFormat = this._gl.RGB_INTEGER;
                        break;
                    case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                        internalFormat = this._gl.RGBA_INTEGER;
                        break;
                }
            }
            return internalFormat;
        };
        /** @hidden */
        Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
            if (this._webGLVersion === 1) {
                if (format !== undefined) {
                    switch (format) {
                        case Engine.TEXTUREFORMAT_ALPHA:
                            return this._gl.ALPHA;
                        case Engine.TEXTUREFORMAT_LUMINANCE:
                            return this._gl.LUMINANCE;
                        case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
                            return this._gl.LUMINANCE_ALPHA;
                    }
                }
                return this._gl.RGBA;
            }
            switch (type) {
                case Engine.TEXTURETYPE_BYTE:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED:
                            return this._gl.R8_SNORM;
                        case Engine.TEXTUREFORMAT_RG:
                            return this._gl.RG8_SNORM;
                        case Engine.TEXTUREFORMAT_RGB:
                            return this._gl.RGB8_SNORM;
                        case Engine.TEXTUREFORMAT_RED_INTEGER:
                            return this._gl.R8I;
                        case Engine.TEXTUREFORMAT_RG_INTEGER:
                            return this._gl.RG8I;
                        case Engine.TEXTUREFORMAT_RGB_INTEGER:
                            return this._gl.RGB8I;
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGBA8I;
                        default:
                            return this._gl.RGBA8_SNORM;
                    }
                case Engine.TEXTURETYPE_UNSIGNED_BYTE:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED:
                            return this._gl.R8;
                        case Engine.TEXTUREFORMAT_RG:
                            return this._gl.RG8;
                        case Engine.TEXTUREFORMAT_RGB:
                            return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
                        case Engine.TEXTUREFORMAT_RGBA:
                            return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
                        case Engine.TEXTUREFORMAT_RED_INTEGER:
                            return this._gl.R8UI;
                        case Engine.TEXTUREFORMAT_RG_INTEGER:
                            return this._gl.RG8UI;
                        case Engine.TEXTUREFORMAT_RGB_INTEGER:
                            return this._gl.RGB8UI;
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGBA8UI;
                        default:
                            return this._gl.RGBA8;
                    }
                case Engine.TEXTURETYPE_SHORT:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED_INTEGER:
                            return this._gl.R16I;
                        case Engine.TEXTUREFORMAT_RG_INTEGER:
                            return this._gl.RG16I;
                        case Engine.TEXTUREFORMAT_RGB_INTEGER:
                            return this._gl.RGB16I;
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGBA16I;
                        default:
                            return this._gl.RGBA16I;
                    }
                case Engine.TEXTURETYPE_UNSIGNED_SHORT:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED_INTEGER:
                            return this._gl.R16UI;
                        case Engine.TEXTUREFORMAT_RG_INTEGER:
                            return this._gl.RG16UI;
                        case Engine.TEXTUREFORMAT_RGB_INTEGER:
                            return this._gl.RGB16UI;
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGBA16UI;
                        default:
                            return this._gl.RGBA16UI;
                    }
                case Engine.TEXTURETYPE_INT:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED_INTEGER:
                            return this._gl.R32I;
                        case Engine.TEXTUREFORMAT_RG_INTEGER:
                            return this._gl.RG32I;
                        case Engine.TEXTUREFORMAT_RGB_INTEGER:
                            return this._gl.RGB32I;
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGBA32I;
                        default:
                            return this._gl.RGBA32I;
                    }
                case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED_INTEGER:
                            return this._gl.R32UI;
                        case Engine.TEXTUREFORMAT_RG_INTEGER:
                            return this._gl.RG32UI;
                        case Engine.TEXTUREFORMAT_RGB_INTEGER:
                            return this._gl.RGB32UI;
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGBA32UI;
                        default:
                            return this._gl.RGBA32UI;
                    }
                case Engine.TEXTURETYPE_FLOAT:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED:
                            return this._gl.R32F; // By default. Other possibility is R16F.
                        case Engine.TEXTUREFORMAT_RG:
                            return this._gl.RG32F; // By default. Other possibility is RG16F.
                        case Engine.TEXTUREFORMAT_RGB:
                            return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
                        case Engine.TEXTUREFORMAT_RGBA:
                            return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
                        default:
                            return this._gl.RGBA32F;
                    }
                case Engine.TEXTURETYPE_HALF_FLOAT:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RED:
                            return this._gl.R16F;
                        case Engine.TEXTUREFORMAT_RG:
                            return this._gl.RG16F;
                        case Engine.TEXTUREFORMAT_RGB:
                            return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
                        case Engine.TEXTUREFORMAT_RGBA:
                            return this._gl.RGBA16F;
                        default:
                            return this._gl.RGBA16F;
                    }
                case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
                    return this._gl.RGB565;
                case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
                    return this._gl.R11F_G11F_B10F;
                case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
                    return this._gl.RGB9_E5;
                case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
                    return this._gl.RGBA4;
                case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
                    return this._gl.RGB5_A1;
                case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
                    switch (format) {
                        case Engine.TEXTUREFORMAT_RGBA:
                            return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
                        case Engine.TEXTUREFORMAT_RGBA_INTEGER:
                            return this._gl.RGB10_A2UI;
                        default:
                            return this._gl.RGB10_A2;
                    }
            }
            return this._gl.RGBA8;
        };
        /** @hidden */
        Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
            if (type === Engine.TEXTURETYPE_FLOAT) {
                return this._gl.RGBA32F;
            }
            else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
                return this._gl.RGBA16F;
            }
            return this._gl.RGBA8;
        };
        /** @hidden */
        Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
            var _this = this;
            var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
            this._activeRequests.push(request);
            request.onCompleteObservable.add(function (request) {
                _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
            });
            return request;
        };
        /** @hidden */
        Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                _this._loadFile(url, function (data) {
                    resolve(data);
                }, undefined, database, useArrayBuffer, function (request, exception) {
                    reject(exception);
                });
            });
        };
        Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
            if (onErrorCallBack === void 0) { onErrorCallBack = null; }
            var onload = function (data) {
                loadedFiles[index] = data;
                loadedFiles._internalCount++;
                if (loadedFiles._internalCount === 6) {
                    onfinish(loadedFiles);
                }
            };
            var onerror = function (request, exception) {
                if (onErrorCallBack && request) {
                    onErrorCallBack(request.status + " " + request.statusText, exception);
                }
            };
            this._loadFile(url, onload, undefined, undefined, true, onerror);
        };
        Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
            if (onError === void 0) { onError = null; }
            var loadedFiles = [];
            loadedFiles._internalCount = 0;
            for (var index = 0; index < 6; index++) {
                this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
            }
        };
        // Statics
        /**
         * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
         * @returns true if the engine can be created
         * @ignorenaming
         */
        Engine.isSupported = function () {
            try {
                var tempcanvas = document.createElement("canvas");
                var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
                return gl != null && !!window.WebGLRenderingContext;
            }
            catch (e) {
                return false;
            }
        };
        /** Use this array to turn off some WebGL2 features on known buggy browsers version */
        Engine.ExceptionList = [
            { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
            { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
            { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
            { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
            { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
            { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
        ];
        /** Gets the list of created engines */
        Engine.Instances = new Array();
        /**
         * Hidden
         */
        Engine._TextureLoaders = [];
        // Const statics
        /** Defines that alpha blending is disabled */
        Engine.ALPHA_DISABLE = 0;
        /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
        Engine.ALPHA_ADD = 1;
        /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
        Engine.ALPHA_COMBINE = 2;
        /** Defines that alpha blending to DEST - SRC * DEST */
        Engine.ALPHA_SUBTRACT = 3;
        /** Defines that alpha blending to SRC * DEST */
        Engine.ALPHA_MULTIPLY = 4;
        /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
        Engine.ALPHA_MAXIMIZED = 5;
        /** Defines that alpha blending to SRC + DEST */
        Engine.ALPHA_ONEONE = 6;
        /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
        Engine.ALPHA_PREMULTIPLIED = 7;
        /**
         * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
         * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
         */
        Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
        /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
        Engine.ALPHA_INTERPOLATE = 9;
        /**
         * Defines that alpha blending to SRC + (1 - SRC) * DEST
         * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
         */
        Engine.ALPHA_SCREENMODE = 10;
        /** Defines that the ressource is not delayed*/
        Engine.DELAYLOADSTATE_NONE = 0;
        /** Defines that the ressource was successfully delay loaded */
        Engine.DELAYLOADSTATE_LOADED = 1;
        /** Defines that the ressource is currently delay loading */
        Engine.DELAYLOADSTATE_LOADING = 2;
        /** Defines that the ressource is delayed and has not started loading */
        Engine.DELAYLOADSTATE_NOTLOADED = 4;
        // Depht or Stencil test Constants.
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
        Engine.NEVER = 0x0200;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
        Engine.ALWAYS = 0x0207;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
        Engine.LESS = 0x0201;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
        Engine.EQUAL = 0x0202;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
        Engine.LEQUAL = 0x0203;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
        Engine.GREATER = 0x0204;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
        Engine.GEQUAL = 0x0206;
        /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
        Engine.NOTEQUAL = 0x0205;
        // Stencil Actions Constants.
        /** Passed to stencilOperation to specify that stencil value must be kept */
        Engine.KEEP = 0x1E00;
        /** Passed to stencilOperation to specify that stencil value must be replaced */
        Engine.REPLACE = 0x1E01;
        /** Passed to stencilOperation to specify that stencil value must be incremented */
        Engine.INCR = 0x1E02;
        /** Passed to stencilOperation to specify that stencil value must be decremented */
        Engine.DECR = 0x1E03;
        /** Passed to stencilOperation to specify that stencil value must be inverted */
        Engine.INVERT = 0x150A;
        /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
        Engine.INCR_WRAP = 0x8507;
        /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
        Engine.DECR_WRAP = 0x8508;
        /** Texture is not repeating outside of 0..1 UVs */
        Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
        /** Texture is repeating outside of 0..1 UVs */
        Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
        /** Texture is repeating and mirrored */
        Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
        /** ALPHA */
        Engine.TEXTUREFORMAT_ALPHA = 0;
        /** LUMINANCE */
        Engine.TEXTUREFORMAT_LUMINANCE = 1;
        /** LUMINANCE_ALPHA */
        Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
        /** RGB */
        Engine.TEXTUREFORMAT_RGB = 4;
        /** RGBA */
        Engine.TEXTUREFORMAT_RGBA = 5;
        /** RED */
        Engine.TEXTUREFORMAT_RED = 6;
        /** RED (2nd reference) */
        Engine.TEXTUREFORMAT_R = 6;
        /** RG */
        Engine.TEXTUREFORMAT_RG = 7;
        /** RED_INTEGER */
        Engine.TEXTUREFORMAT_RED_INTEGER = 8;
        /** RED_INTEGER (2nd reference) */
        Engine.TEXTUREFORMAT_R_INTEGER = 8;
        /** RG_INTEGER */
        Engine.TEXTUREFORMAT_RG_INTEGER = 9;
        /** RGB_INTEGER */
        Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
        /** RGBA_INTEGER */
        Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
        /** UNSIGNED_BYTE */
        Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
        /** UNSIGNED_BYTE (2nd reference) */
        Engine.TEXTURETYPE_UNSIGNED_INT = 0;
        /** FLOAT */
        Engine.TEXTURETYPE_FLOAT = 1;
        /** HALF_FLOAT */
        Engine.TEXTURETYPE_HALF_FLOAT = 2;
        /** BYTE */
        Engine.TEXTURETYPE_BYTE = 3;
        /** SHORT */
        Engine.TEXTURETYPE_SHORT = 4;
        /** UNSIGNED_SHORT */
        Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
        /** INT */
        Engine.TEXTURETYPE_INT = 6;
        /** UNSIGNED_INT */
        Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
        /** UNSIGNED_SHORT_4_4_4_4 */
        Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
        /** UNSIGNED_SHORT_5_5_5_1 */
        Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
        /** UNSIGNED_SHORT_5_6_5 */
        Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
        /** UNSIGNED_INT_2_10_10_10_REV */
        Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
        /** UNSIGNED_INT_24_8 */
        Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
        /** UNSIGNED_INT_10F_11F_11F_REV */
        Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
        /** UNSIGNED_INT_5_9_9_9_REV */
        Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
        /** FLOAT_32_UNSIGNED_INT_24_8_REV */
        Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
        /** nearest is mag = nearest and min = nearest and mip = linear */
        Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
        /** Bilinear is mag = linear and min = linear and mip = nearest */
        Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
        /** Trilinear is mag = linear and min = linear and mip = linear */
        Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
        /** nearest is mag = nearest and min = nearest and mip = linear */
        Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
        /** Bilinear is mag = linear and min = linear and mip = nearest */
        Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
        /** Trilinear is mag = linear and min = linear and mip = linear */
        Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
        /** mag = nearest and min = nearest and mip = nearest */
        Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
        /** mag = nearest and min = linear and mip = nearest */
        Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
        /** mag = nearest and min = linear and mip = linear */
        Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
        /** mag = nearest and min = linear and mip = none */
        Engine.TEXTURE_NEAREST_LINEAR = 7;
        /** mag = nearest and min = nearest and mip = none */
        Engine.TEXTURE_NEAREST_NEAREST = 8;
        /** mag = linear and min = nearest and mip = nearest */
        Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
        /** mag = linear and min = nearest and mip = linear */
        Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
        /** mag = linear and min = linear and mip = none */
        Engine.TEXTURE_LINEAR_LINEAR = 11;
        /** mag = linear and min = nearest and mip = none */
        Engine.TEXTURE_LINEAR_NEAREST = 12;
        /** Explicit coordinates mode */
        Engine.TEXTURE_EXPLICIT_MODE = 0;
        /** Spherical coordinates mode */
        Engine.TEXTURE_SPHERICAL_MODE = 1;
        /** Planar coordinates mode */
        Engine.TEXTURE_PLANAR_MODE = 2;
        /** Cubic coordinates mode */
        Engine.TEXTURE_CUBIC_MODE = 3;
        /** Projection coordinates mode */
        Engine.TEXTURE_PROJECTION_MODE = 4;
        /** Skybox coordinates mode */
        Engine.TEXTURE_SKYBOX_MODE = 5;
        /** Inverse Cubic coordinates mode */
        Engine.TEXTURE_INVCUBIC_MODE = 6;
        /** Equirectangular coordinates mode */
        Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
        /** Equirectangular Fixed coordinates mode */
        Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
        /** Equirectangular Fixed Mirrored coordinates mode */
        Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
        // Texture rescaling mode
        /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
        Engine.SCALEMODE_FLOOR = 1;
        /** Defines that texture rescaling will look for the nearest power of 2 size */
        Engine.SCALEMODE_NEAREST = 2;
        /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
        Engine.SCALEMODE_CEILING = 3;
        // Updatable statics so stick with vars here
        /**
         * Gets or sets the epsilon value used by collision engine
         */
        Engine.CollisionsEpsilon = 0.001;
        /**
         * Gets or sets the relative url used to load code if using the engine in non-minified mode
         */
        Engine.CodeRepository = "src/";
        /**
         * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
         */
        Engine.ShadersRepository = "src/Shaders/";
        return Engine;
    }());
    BABYLON.Engine = Engine;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.engine.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Node is the basic class for all scene objects (Mesh, Light, Camera.)
     */
    var Node = /** @class */ (function () {
        /**
         * Creates a new Node
         * @param name the name and id to be given to this node
         * @param scene the scene this node will be added to
         */
        function Node(name, scene) {
            if (scene === void 0) { scene = null; }
            /**
             * Gets or sets a string used to store user defined state for the node
             */
            this.state = "";
            /**
             * Gets or sets an object used to store user defined information for the node
             */
            this.metadata = null;
            /**
             * Gets or sets a boolean used to define if the node must be serialized
             */
            this.doNotSerialize = false;
            /** @hidden */
            this._isDisposed = false;
            /**
             * Gets a list of Animations associated with the node
             */
            this.animations = new Array();
            this._ranges = {};
            this._isEnabled = true;
            this._isParentEnabled = true;
            this._isReady = true;
            /** @hidden */
            this._currentRenderId = -1;
            this._parentRenderId = -1;
            this._childRenderId = -1;
            /** @hidden */
            this._worldMatrix = BABYLON.Matrix.Identity();
            /** @hidden */
            this._worldMatrixDeterminant = 0;
            /** @hidden */
            this._sceneRootNodesIndex = -1;
            this._animationPropertiesOverride = null;
            /**
            * An event triggered when the mesh is disposed
            */
            this.onDisposeObservable = new BABYLON.Observable();
            // Behaviors
            this._behaviors = new Array();
            this.name = name;
            this.id = name;
            this._scene = (scene || BABYLON.Engine.LastCreatedScene);
            this.uniqueId = this._scene.getUniqueId();
            this._initCache();
            this.addToSceneRootNodes();
        }
        /**
         * Add a new node constructor
         * @param type defines the type name of the node to construct
         * @param constructorFunc defines the constructor function
         */
        Node.AddNodeConstructor = function (type, constructorFunc) {
            this._NodeConstructors[type] = constructorFunc;
        };
        /**
         * Returns a node constructor based on type name
         * @param type defines the type name
         * @param name defines the new node name
         * @param scene defines the hosting scene
         * @param options defines optional options to transmit to constructors
         * @returns the new constructor or null
         */
        Node.Construct = function (type, name, scene, options) {
            var constructorFunc = this._NodeConstructors[type];
            if (!constructorFunc) {
                return null;
            }
            return constructorFunc(name, scene, options);
        };
        /**
         * Gets a boolean indicating if the node has been disposed
         * @returns true if the node was disposed
         */
        Node.prototype.isDisposed = function () {
            return this._isDisposed;
        };
        Object.defineProperty(Node.prototype, "parent", {
            get: function () {
                return this._parentNode;
            },
            /**
             * Gets or sets the parent of the node
             */
            set: function (parent) {
                if (this._parentNode === parent) {
                    return;
                }
                var previousParentNode = this._parentNode;
                // Remove self from list of children of parent
                if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
                    var index = this._parentNode._children.indexOf(this);
                    if (index !== -1) {
                        this._parentNode._children.splice(index, 1);
                    }
                    if (!parent) {
                        this.addToSceneRootNodes();
                    }
                }
                // Store new parent
                this._parentNode = parent;
                // Add as child to new parent
                if (this._parentNode) {
                    if (this._parentNode._children === undefined || this._parentNode._children === null) {
                        this._parentNode._children = new Array();
                    }
                    this._parentNode._children.push(this);
                    if (!previousParentNode) {
                        this.removeFromSceneRootNodes();
                    }
                }
                // Enabled state
                this._syncParentEnabledState();
            },
            enumerable: true,
            configurable: true
        });
        Node.prototype.addToSceneRootNodes = function () {
            if (this._sceneRootNodesIndex === -1) {
                this._sceneRootNodesIndex = this._scene.rootNodes.length;
                this._scene.rootNodes.push(this);
            }
        };
        Node.prototype.removeFromSceneRootNodes = function () {
            if (this._sceneRootNodesIndex !== -1) {
                var rootNodes = this._scene.rootNodes;
                var lastIdx = rootNodes.length - 1;
                rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
                rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
                this._scene.rootNodes.pop();
                this._sceneRootNodesIndex = -1;
            }
        };
        Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
            /**
             * Gets or sets the animation properties override
             */
            get: function () {
                if (!this._animationPropertiesOverride) {
                    return this._scene.animationPropertiesOverride;
                }
                return this._animationPropertiesOverride;
            },
            set: function (value) {
                this._animationPropertiesOverride = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets a string idenfifying the name of the class
         * @returns "Node" string
         */
        Node.prototype.getClassName = function () {
            return "Node";
        };
        Object.defineProperty(Node.prototype, "onDispose", {
            /**
             * Sets a callback that will be raised when the node will be disposed
             */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the scene of the node
         * @returns a scene
         */
        Node.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Gets the engine of the node
         * @returns a Engine
         */
        Node.prototype.getEngine = function () {
            return this._scene.getEngine();
        };
        /**
         * Attach a behavior to the node
         * @see http://doc.babylonjs.com/features/behaviour
         * @param behavior defines the behavior to attach
         * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
         * @returns the current Node
         */
        Node.prototype.addBehavior = function (behavior, attachImmediately) {
            var _this = this;
            if (attachImmediately === void 0) { attachImmediately = false; }
            var index = this._behaviors.indexOf(behavior);
            if (index !== -1) {
                return this;
            }
            behavior.init();
            if (this._scene.isLoading && !attachImmediately) {
                // We defer the attach when the scene will be loaded
                this._scene.onDataLoadedObservable.addOnce(function () {
                    behavior.attach(_this);
                });
            }
            else {
                behavior.attach(this);
            }
            this._behaviors.push(behavior);
            return this;
        };
        /**
         * Remove an attached behavior
         * @see http://doc.babylonjs.com/features/behaviour
         * @param behavior defines the behavior to attach
         * @returns the current Node
         */
        Node.prototype.removeBehavior = function (behavior) {
            var index = this._behaviors.indexOf(behavior);
            if (index === -1) {
                return this;
            }
            this._behaviors[index].detach();
            this._behaviors.splice(index, 1);
            return this;
        };
        Object.defineProperty(Node.prototype, "behaviors", {
            /**
             * Gets the list of attached behaviors
             * @see http://doc.babylonjs.com/features/behaviour
             */
            get: function () {
                return this._behaviors;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets an attached behavior by name
         * @param name defines the name of the behavior to look for
         * @see http://doc.babylonjs.com/features/behaviour
         * @returns null if behavior was not found else the requested behavior
         */
        Node.prototype.getBehaviorByName = function (name) {
            for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
                var behavior = _a[_i];
                if (behavior.name === name) {
                    return behavior;
                }
            }
            return null;
        };
        /**
         * Returns the latest update of the World matrix
         * @returns a Matrix
         */
        Node.prototype.getWorldMatrix = function () {
            if (this._currentRenderId !== this._scene.getRenderId()) {
                this.computeWorldMatrix();
            }
            return this._worldMatrix;
        };
        /** @hidden */
        Node.prototype._getWorldMatrixDeterminant = function () {
            return this._worldMatrixDeterminant;
        };
        Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
            /**
             * Returns directly the latest state of the mesh World matrix.
             * A Matrix is returned.
             */
            get: function () {
                return this._worldMatrix;
            },
            enumerable: true,
            configurable: true
        });
        // override it in derived class if you add new variables to the cache
        // and call the parent class method
        /** @hidden */
        Node.prototype._initCache = function () {
            this._cache = {};
            this._cache.parent = undefined;
        };
        /** @hidden */
        Node.prototype.updateCache = function (force) {
            if (!force && this.isSynchronized()) {
                return;
            }
            this._cache.parent = this.parent;
            this._updateCache();
        };
        // override it in derived class if you add new variables to the cache
        // and call the parent class method if !ignoreParentClass
        /** @hidden */
        Node.prototype._updateCache = function (ignoreParentClass) {
        };
        // override it in derived class if you add new variables to the cache
        /** @hidden */
        Node.prototype._isSynchronized = function () {
            return true;
        };
        /** @hidden */
        Node.prototype._markSyncedWithParent = function () {
            if (this._parentNode) {
                this._parentRenderId = this._parentNode._childRenderId;
            }
        };
        /** @hidden */
        Node.prototype.isSynchronizedWithParent = function () {
            if (!this._parentNode) {
                return true;
            }
            if (this._parentRenderId !== this._parentNode._childRenderId) {
                return false;
            }
            return this._parentNode.isSynchronized();
        };
        /** @hidden */
        Node.prototype.isSynchronized = function () {
            if (this._cache.parent != this._parentNode) {
                this._cache.parent = this._parentNode;
                return false;
            }
            if (this._parentNode && !this.isSynchronizedWithParent()) {
                return false;
            }
            return this._isSynchronized();
        };
        /**
         * Is this node ready to be used/rendered
         * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
         * @return true if the node is ready
         */
        Node.prototype.isReady = function (completeCheck) {
            if (completeCheck === void 0) { completeCheck = false; }
            return this._isReady;
        };
        /**
         * Is this node enabled?
         * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true
         * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors
         * @return whether this node (and its parent) is enabled
         */
        Node.prototype.isEnabled = function (checkAncestors) {
            if (checkAncestors === void 0) { checkAncestors = true; }
            if (checkAncestors === false) {
                return this._isEnabled;
            }
            if (!this._isEnabled) {
                return false;
            }
            return this._isParentEnabled;
        };
        /** @hidden */
        Node.prototype._syncParentEnabledState = function () {
            this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
            if (this._children) {
                this._children.forEach(function (c) {
                    c._syncParentEnabledState(); // Force children to update accordingly
                });
            }
        };
        /**
         * Set the enabled state of this node
         * @param value defines the new enabled state
         */
        Node.prototype.setEnabled = function (value) {
            this._isEnabled = value;
            this._syncParentEnabledState();
        };
        /**
         * Is this node a descendant of the given node?
         * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
         * @param ancestor defines the parent node to inspect
         * @returns a boolean indicating if this node is a descendant of the given node
         */
        Node.prototype.isDescendantOf = function (ancestor) {
            if (this.parent) {
                if (this.parent === ancestor) {
                    return true;
                }
                return this.parent.isDescendantOf(ancestor);
            }
            return false;
        };
        /** @hidden */
        Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
            if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
            if (!this._children) {
                return;
            }
            for (var index = 0; index < this._children.length; index++) {
                var item = this._children[index];
                if (!predicate || predicate(item)) {
                    results.push(item);
                }
                if (!directDescendantsOnly) {
                    item._getDescendants(results, false, predicate);
                }
            }
        };
        /**
         * Will return all nodes that have this node as ascendant
         * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
         * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
         * @return all children nodes of all types
         */
        Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
            var results = new Array();
            this._getDescendants(results, directDescendantsOnly, predicate);
            return results;
        };
        /**
         * Get all child-meshes of this node
         * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
         * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
         * @returns an array of AbstractMesh
         */
        Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
            var results = [];
            this._getDescendants(results, directDescendantsOnly, function (node) {
                return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
            });
            return results;
        };
        /**
         * Get all child-transformNodes of this node
         * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
         * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
         * @returns an array of TransformNode
         */
        Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
            var results = [];
            this._getDescendants(results, directDescendantsOnly, function (node) {
                return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
            });
            return results;
        };
        /**
         * Get all direct children of this node
         * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
         * @returns an array of Node
         */
        Node.prototype.getChildren = function (predicate) {
            return this.getDescendants(true, predicate);
        };
        /** @hidden */
        Node.prototype._setReady = function (state) {
            if (state === this._isReady) {
                return;
            }
            if (!state) {
                this._isReady = false;
                return;
            }
            if (this.onReady) {
                this.onReady(this);
            }
            this._isReady = true;
        };
        /**
         * Get an animation by name
         * @param name defines the name of the animation to look for
         * @returns null if not found else the requested animation
         */
        Node.prototype.getAnimationByName = function (name) {
            for (var i = 0; i < this.animations.length; i++) {
                var animation = this.animations[i];
                if (animation.name === name) {
                    return animation;
                }
            }
            return null;
        };
        /**
         * Creates an animation range for this node
         * @param name defines the name of the range
         * @param from defines the starting key
         * @param to defines the end key
         */
        Node.prototype.createAnimationRange = function (name, from, to) {
            // check name not already in use
            if (!this._ranges[name]) {
                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
                for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
                    if (this.animations[i]) {
                        this.animations[i].createRange(name, from, to);
                    }
                }
            }
        };
        /**
         * Delete a specific animation range
         * @param name defines the name of the range to delete
         * @param deleteFrames defines if animation frames from the range must be deleted as well
         */
        Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
            if (deleteFrames === void 0) { deleteFrames = true; }
            for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
                if (this.animations[i]) {
                    this.animations[i].deleteRange(name, deleteFrames);
                }
            }
            this._ranges[name] = null; // said much faster than 'delete this._range[name]'
        };
        /**
         * Get an animation range by name
         * @param name defines the name of the animation range to look for
         * @returns null if not found else the requested animation range
         */
        Node.prototype.getAnimationRange = function (name) {
            return this._ranges[name];
        };
        /**
         * Will start the animation sequence
         * @param name defines the range frames for animation sequence
         * @param loop defines if the animation should loop (false by default)
         * @param speedRatio defines the speed factor in which to run the animation (1 by default)
         * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
         * @returns the object created for this animation. If range does not exist, it will return null
         */
        Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
            var range = this.getAnimationRange(name);
            if (!range) {
                return null;
            }
            return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
        };
        /**
         * Serialize animation ranges into a JSON compatible object
         * @returns serialization object
         */
        Node.prototype.serializeAnimationRanges = function () {
            var serializationRanges = [];
            for (var name in this._ranges) {
                var localRange = this._ranges[name];
                if (!localRange) {
                    continue;
                }
                var range = {};
                range.name = name;
                range.from = localRange.from;
                range.to = localRange.to;
                serializationRanges.push(range);
            }
            return serializationRanges;
        };
        /**
         * Computes the world matrix of the node
         * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
         * @returns the world matrix
         */
        Node.prototype.computeWorldMatrix = function (force) {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            return this._worldMatrix;
        };
        /**
         * Releases resources associated with this node.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            if (!doNotRecurse) {
                var nodes = this.getDescendants(true);
                for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
                    var node = nodes_1[_i];
                    node.dispose(doNotRecurse, disposeMaterialAndTextures);
                }
            }
            else {
                var transformNodes = this.getChildTransformNodes(true);
                for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
                    var transformNode = transformNodes_1[_a];
                    transformNode.parent = null;
                    transformNode.computeWorldMatrix(true);
                }
            }
            if (!this.parent) {
                this.removeFromSceneRootNodes();
            }
            else {
                this.parent = null;
            }
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            // Behaviors
            for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
                var behavior = _c[_b];
                behavior.detach();
            }
            this._behaviors = [];
            this._isDisposed = true;
        };
        /**
         * Parse animation range data from a serialization object and store them into a given node
         * @param node defines where to store the animation ranges
         * @param parsedNode defines the serialization object to read data from
         * @param scene defines the hosting scene
         */
        Node.ParseAnimationRanges = function (node, parsedNode, scene) {
            if (parsedNode.ranges) {
                for (var index = 0; index < parsedNode.ranges.length; index++) {
                    var data = parsedNode.ranges[index];
                    node.createAnimationRange(data.name, data.from, data.to);
                }
            }
        };
        Node._NodeConstructors = {};
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "name", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "id", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "uniqueId", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "state", void 0);
        __decorate([
            BABYLON.serialize()
        ], Node.prototype, "metadata", void 0);
        return Node;
    }());
    BABYLON.Node = Node;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.node.js.map

var BABYLON;
(function (BABYLON) {
    // This matrix is used as a value to reset the bounding box.
    var _identityMatrix = BABYLON.Matrix.Identity();
    /**
     * Class used to store bounding sphere information
     */
    var BoundingSphere = /** @class */ (function () {
        /**
         * Creates a new bounding sphere
         * @param min defines the minimum vector (in local space)
         * @param max defines the maximum vector (in local space)
         */
        function BoundingSphere(min, max) {
            /**
             * Gets the center of the bounding sphere in local space
             */
            this.center = BABYLON.Vector3.Zero();
            /**
             * Gets the center of the bounding sphere in world space
             */
            this.centerWorld = BABYLON.Vector3.Zero();
            /**
             * Gets the minimum vector in local space
             */
            this.minimum = BABYLON.Vector3.Zero();
            /**
             * Gets the maximum vector in local space
             */
            this.maximum = BABYLON.Vector3.Zero();
            this.reConstruct(min, max);
        }
        /**
         * Recreates the entire bounding sphere from scratch
         * @param min defines the new minimum vector (in local space)
         * @param max defines the new maximum vector (in local space)
         */
        BoundingSphere.prototype.reConstruct = function (min, max) {
            this.minimum.copyFrom(min);
            this.maximum.copyFrom(max);
            var distance = BABYLON.Vector3.Distance(min, max);
            BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
            this.radius = distance * 0.5;
            this.centerWorld.set(0, 0, 0);
            this._update(_identityMatrix);
        };
        /**
         * Scale the current bounding sphere by applying a scale factor
         * @param factor defines the scale factor to apply
         * @returns the current bounding box
         */
        BoundingSphere.prototype.scale = function (factor) {
            var newRadius = this.radius * factor;
            var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
            var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
            var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
            this.reConstruct(min, max);
            return this;
        };
        // Methods
        /** @hidden */
        BoundingSphere.prototype._update = function (world) {
            BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
            var tempVector = BABYLON.Tmp.Vector3[0];
            BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
            this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
        };
        /**
         * Tests if the bounding sphere is intersecting the frustum planes
         * @param frustumPlanes defines the frustum planes to test
         * @returns true if there is an intersection
         */
        BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
            for (var i = 0; i < 6; i++) {
                if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld) {
                    return false;
                }
            }
            return true;
        };
        /**
         * Tests if a point is inside the bounding sphere
         * @param point defines the point to test
         * @returns true if the point is inside the bounding sphere
         */
        BoundingSphere.prototype.intersectsPoint = function (point) {
            var x = this.centerWorld.x - point.x;
            var y = this.centerWorld.y - point.y;
            var z = this.centerWorld.z - point.z;
            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
            if (this.radiusWorld < distance) {
                return false;
            }
            return true;
        };
        // Statics
        /**
         * Checks if two sphere intersct
         * @param sphere0 sphere 0
         * @param sphere1 sphere 1
         * @returns true if the speres intersect
         */
        BoundingSphere.Intersects = function (sphere0, sphere1) {
            var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
            var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
            var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
            var distance = Math.sqrt((x * x) + (y * y) + (z * z));
            if (sphere0.radiusWorld + sphere1.radiusWorld < distance) {
                return false;
            }
            return true;
        };
        return BoundingSphere;
    }());
    BABYLON.BoundingSphere = BoundingSphere;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boundingSphere.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store bounding box information
     */
    var BoundingBox = /** @class */ (function () {
        /**
         * Creates a new bounding box
         * @param min defines the minimum vector (in local space)
         * @param max defines the maximum vector (in local space)
         */
        function BoundingBox(min, max) {
            /**
             * Gets the 8 vectors representing the bounding box in local space
             */
            this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
            /**
             * Gets the center of the bounding box in local space
             */
            this.center = BABYLON.Vector3.Zero();
            /**
             * Gets the center of the bounding box in world space
             */
            this.centerWorld = BABYLON.Vector3.Zero();
            /**
             * Gets the extend size in local space
             */
            this.extendSize = BABYLON.Vector3.Zero();
            /**
             * Gets the extend size in world space
             */
            this.extendSizeWorld = BABYLON.Vector3.Zero();
            /**
             * Gets the OBB (object bounding box) directions
             */
            this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
            /**
             * Gets the 8 vectors representing the bounding box in world space
             */
            this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
            /**
             * Gets the minimum vector in world space
             */
            this.minimumWorld = BABYLON.Vector3.Zero();
            /**
             * Gets the maximum vector in world space
             */
            this.maximumWorld = BABYLON.Vector3.Zero();
            /**
             * Gets the minimum vector in local space
             */
            this.minimum = BABYLON.Vector3.Zero();
            /**
             * Gets the maximum vector in local space
             */
            this.maximum = BABYLON.Vector3.Zero();
            this.reConstruct(min, max);
        }
        // Methods
        /**
         * Recreates the entire bounding box from scratch
         * @param min defines the new minimum vector (in local space)
         * @param max defines the new maximum vector (in local space)
         */
        BoundingBox.prototype.reConstruct = function (min, max) {
            this.minimum.copyFrom(min);
            this.maximum.copyFrom(max);
            // Bounding vectors
            this.vectors[0].copyFrom(this.minimum);
            this.vectors[1].copyFrom(this.maximum);
            this.vectors[2].copyFrom(this.minimum);
            this.vectors[3].copyFrom(this.minimum);
            this.vectors[4].copyFrom(this.minimum);
            this.vectors[5].copyFrom(this.maximum);
            this.vectors[6].copyFrom(this.maximum);
            this.vectors[7].copyFrom(this.maximum);
            this.vectors[2].x = this.maximum.x;
            this.vectors[3].y = this.maximum.y;
            this.vectors[4].z = this.maximum.z;
            this.vectors[5].z = this.minimum.z;
            this.vectors[6].x = this.minimum.x;
            this.vectors[7].y = this.minimum.y;
            // OBB
            this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
            this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
            for (var index = 0; index < 3; index++) {
                this.directions[index].copyFromFloats(0, 0, 0);
            }
            // World
            for (var index = 0; index < 8; index++) {
                this.vectorsWorld[index].copyFromFloats(0, 0, 0);
            }
            this.minimumWorld.copyFromFloats(0, 0, 0);
            this.maximumWorld.copyFromFloats(0, 0, 0);
            this.centerWorld.copyFromFloats(0, 0, 0);
            this.extendSizeWorld.copyFromFloats(0, 0, 0);
            this._update(this._worldMatrix || BABYLON.Matrix.Identity());
        };
        /**
         * Scale the current bounding box by applying a scale factor
         * @param factor defines the scale factor to apply
         * @returns the current bounding box
         */
        BoundingBox.prototype.scale = function (factor) {
            var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
            var distance = diff.length() * factor;
            diff.normalize();
            var newRadius = diff.scaleInPlace(distance * 0.5);
            var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
            var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
            this.reConstruct(min, max);
            return this;
        };
        /**
         * Gets the world matrix of the bounding box
         * @returns a matrix
         */
        BoundingBox.prototype.getWorldMatrix = function () {
            return this._worldMatrix;
        };
        /**
         * Sets the world matrix stored in the bounding box
         * @param matrix defines the matrix to store
         * @returns current bounding box
         */
        BoundingBox.prototype.setWorldMatrix = function (matrix) {
            this._worldMatrix.copyFrom(matrix);
            return this;
        };
        /** @hidden */
        BoundingBox.prototype._update = function (world) {
            BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
            BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
            for (var index = 0; index < 8; index++) {
                var v = this.vectorsWorld[index];
                BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
                this.minimumWorld.minimizeInPlace(v);
                this.maximumWorld.maximizeInPlace(v);
            }
            // Extend
            this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
            this.extendSizeWorld.scaleInPlace(0.5);
            // OBB
            this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
            this.centerWorld.scaleInPlace(0.5);
            BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
            BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
            BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
            this._worldMatrix = world;
        };
        /**
         * Tests if the bounding box is intersecting the frustum planes
         * @param frustumPlanes defines the frustum planes to test
         * @returns true if there is an intersection
         */
        BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
            return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
        };
        /**
         * Tests if the bounding box is entirely inside the frustum planes
         * @param frustumPlanes defines the frustum planes to test
         * @returns true if there is an inclusion
         */
        BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
        };
        /**
         * Tests if a point is inside the bounding box
         * @param point defines the point to test
         * @returns true if the point is inside the bounding box
         */
        BoundingBox.prototype.intersectsPoint = function (point) {
            var delta = -BABYLON.Epsilon;
            if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x) {
                return false;
            }
            if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y) {
                return false;
            }
            if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z) {
                return false;
            }
            return true;
        };
        /**
         * Tests if the bounding box intersects with a bounding sphere
         * @param sphere defines the sphere to test
         * @returns true if there is an intersection
         */
        BoundingBox.prototype.intersectsSphere = function (sphere) {
            return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
        };
        /**
         * Tests if the bounding box intersects with a box defined by a min and max vectors
         * @param min defines the min vector to use
         * @param max defines the max vector to use
         * @returns true if there is an intersection
         */
        BoundingBox.prototype.intersectsMinMax = function (min, max) {
            if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x) {
                return false;
            }
            if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y) {
                return false;
            }
            if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z) {
                return false;
            }
            return true;
        };
        // Statics
        /**
         * Tests if two bounding boxes are intersections
         * @param box0 defines the first box to test
         * @param box1 defines the second box to test
         * @returns true if there is an intersection
         */
        BoundingBox.Intersects = function (box0, box1) {
            if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x) {
                return false;
            }
            if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y) {
                return false;
            }
            if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z) {
                return false;
            }
            return true;
        };
        /**
         * Tests if a bounding box defines by a min/max vectors intersects a sphere
         * @param minPoint defines the minimum vector of the bounding box
         * @param maxPoint defines the maximum vector of the bounding box
         * @param sphereCenter defines the sphere center
         * @param sphereRadius defines the sphere radius
         * @returns true if there is an intersection
         */
        BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
            var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
            var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
            return (num <= (sphereRadius * sphereRadius));
        };
        /**
         * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
         * @param boundingVectors defines an array of 8 vectors representing a bounding box
         * @param frustumPlanes defines the frustum planes to test
         * @return true if there is an inclusion
         */
        BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
            for (var p = 0; p < 6; p++) {
                for (var i = 0; i < 8; i++) {
                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
                        return false;
                    }
                }
            }
            return true;
        };
        /**
         * Tests if a bounding box defined with 8 vectors intersects frustum planes
         * @param boundingVectors defines an array of 8 vectors representing a bounding box
         * @param frustumPlanes defines the frustum planes to test
         * @return true if there is an intersection
         */
        BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
            for (var p = 0; p < 6; p++) {
                var inCount = 8;
                for (var i = 0; i < 8; i++) {
                    if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
                        --inCount;
                    }
                    else {
                        break;
                    }
                }
                if (inCount === 0) {
                    return false;
                }
            }
            return true;
        };
        return BoundingBox;
    }());
    BABYLON.BoundingBox = BoundingBox;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boundingBox.js.map

var BABYLON;
(function (BABYLON) {
    var computeBoxExtents = function (axis, box) {
        var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
        var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
        var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
        var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
        var r = r0 + r1 + r2;
        return {
            min: p - r,
            max: p + r
        };
    };
    var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
    var axisOverlap = function (axis, box0, box1) {
        var result0 = computeBoxExtents(axis, box0);
        var result1 = computeBoxExtents(axis, box1);
        return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
    };
    /**
     * Info for a bounding data of a mesh
     */
    var BoundingInfo = /** @class */ (function () {
        /**
         * Constructs bounding info
         * @param minimum min vector of the bounding box/sphere
         * @param maximum max vector of the bounding box/sphere
         */
        function BoundingInfo(minimum, maximum) {
            this._isLocked = false;
            this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
            this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
        }
        Object.defineProperty(BoundingInfo.prototype, "minimum", {
            /**
             * min vector of the bounding box/sphere
             */
            get: function () {
                return this.boundingBox.minimum;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BoundingInfo.prototype, "maximum", {
            /**
             * max vector of the bounding box/sphere
             */
            get: function () {
                return this.boundingBox.maximum;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BoundingInfo.prototype, "isLocked", {
            /**
             * If the info is locked and won't be updated to avoid perf overhead
             */
            get: function () {
                return this._isLocked;
            },
            set: function (value) {
                this._isLocked = value;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * Updates the boudning sphere and box
         * @param world world matrix to be used to update
         */
        BoundingInfo.prototype.update = function (world) {
            if (this._isLocked) {
                return;
            }
            this.boundingBox._update(world);
            this.boundingSphere._update(world);
        };
        /**
         * Recreate the bounding info to be centered around a specific point given a specific extend.
         * @param center New center of the bounding info
         * @param extend New extend of the bounding info
         * @returns the current bounding info
         */
        BoundingInfo.prototype.centerOn = function (center, extend) {
            var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
            var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
            this.boundingBox.reConstruct(minimum, maximum);
            this.boundingSphere.reConstruct(minimum, maximum);
            return this;
        };
        /**
         * Scale the current bounding info by applying a scale factor
         * @param factor defines the scale factor to apply
         * @returns the current bounding info
         */
        BoundingInfo.prototype.scale = function (factor) {
            this.boundingBox.scale(factor);
            this.boundingSphere.scale(factor);
            return this;
        };
        /**
         * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
         * @param frustumPlanes defines the frustum to test
         * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
         * @returns true if the bounding info is in the frustum planes
         */
        BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
            if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
            if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
                return false;
            }
            if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
                return true;
            }
            return this.boundingBox.isInFrustum(frustumPlanes);
        };
        Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
            /**
             * Gets the world distance between the min and max points of the bounding box
             */
            get: function () {
                var boundingBox = this.boundingBox;
                var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
                return size.length();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Checks if a cullable object (mesh...) is in the camera frustum
         * Unlike isInFrustum this cheks the full bounding box
         * @param frustumPlanes Camera near/planes
         * @returns true if the object is in frustum otherwise false
         */
        BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
        };
        /** @hidden */
        BoundingInfo.prototype._checkCollision = function (collider) {
            return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
        };
        /**
         * Checks if a point is inside the bounding box and bounding sphere or the mesh
         * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
         * @param point the point to check intersection with
         * @returns if the point intersects
         */
        BoundingInfo.prototype.intersectsPoint = function (point) {
            if (!this.boundingSphere.centerWorld) {
                return false;
            }
            if (!this.boundingSphere.intersectsPoint(point)) {
                return false;
            }
            if (!this.boundingBox.intersectsPoint(point)) {
                return false;
            }
            return true;
        };
        /**
         * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
         * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
         * @param boundingInfo the bounding info to check intersection with
         * @param precise if the intersection should be done using OBB
         * @returns if the bounding info intersects
         */
        BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
            if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
                return false;
            }
            if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
                return false;
            }
            if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
                return false;
            }
            if (!precise) {
                return true;
            }
            var box0 = this.boundingBox;
            var box1 = boundingInfo.boundingBox;
            if (!axisOverlap(box0.directions[0], box0, box1)) {
                return false;
            }
            if (!axisOverlap(box0.directions[1], box0, box1)) {
                return false;
            }
            if (!axisOverlap(box0.directions[2], box0, box1)) {
                return false;
            }
            if (!axisOverlap(box1.directions[0], box0, box1)) {
                return false;
            }
            if (!axisOverlap(box1.directions[1], box0, box1)) {
                return false;
            }
            if (!axisOverlap(box1.directions[2], box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
                return false;
            }
            if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
                return false;
            }
            return true;
        };
        return BoundingInfo;
    }());
    BABYLON.BoundingInfo = BoundingInfo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boundingInfo.js.map



var BABYLON;
(function (BABYLON) {
    /**
     * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
     * @see https://doc.babylonjs.com/how_to/transformnode
     */
    var TransformNode = /** @class */ (function (_super) {
        __extends(TransformNode, _super);
        function TransformNode(name, scene, isPure) {
            if (scene === void 0) { scene = null; }
            if (isPure === void 0) { isPure = true; }
            var _this = _super.call(this, name, scene) || this;
            _this._forward = new BABYLON.Vector3(0, 0, 1);
            _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
            _this._up = new BABYLON.Vector3(0, 1, 0);
            _this._right = new BABYLON.Vector3(1, 0, 0);
            _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
            // Properties
            _this._position = BABYLON.Vector3.Zero();
            _this._rotation = BABYLON.Vector3.Zero();
            _this._scaling = BABYLON.Vector3.One();
            _this._isDirty = false;
            /**
            * Set the billboard mode. Default is 0.
            *
            * | Value | Type | Description |
            * | --- | --- | --- |
            * | 0 | BILLBOARDMODE_NONE |  |
            * | 1 | BILLBOARDMODE_X |  |
            * | 2 | BILLBOARDMODE_Y |  |
            * | 4 | BILLBOARDMODE_Z |  |
            * | 7 | BILLBOARDMODE_ALL |  |
            *
            */
            _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
            /**
             * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
             */
            _this.scalingDeterminant = 1;
            /**
             * Sets the distance of the object to max, often used by skybox
             */
            _this.infiniteDistance = false;
            /**
             * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
             * By default the system will update normals to compensate
             */
            _this.ignoreNonUniformScaling = false;
            _this._localWorld = BABYLON.Matrix.Zero();
            _this._absolutePosition = BABYLON.Vector3.Zero();
            _this._pivotMatrix = BABYLON.Matrix.Identity();
            _this._postMultiplyPivotMatrix = false;
            _this._isWorldMatrixFrozen = false;
            /**
            * An event triggered after the world matrix is updated
            */
            _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
            _this._nonUniformScaling = false;
            if (isPure) {
                _this.getScene().addTransformNode(_this);
            }
            return _this;
        }
        /**
         * Gets a string identifying the name of the class
         * @returns "TransformNode" string
         */
        TransformNode.prototype.getClassName = function () {
            return "TransformNode";
        };
        Object.defineProperty(TransformNode.prototype, "position", {
            /**
              * Gets or set the node position (default is (0.0, 0.0, 0.0))
              */
            get: function () {
                return this._position;
            },
            set: function (newPosition) {
                this._position = newPosition;
                this._isDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TransformNode.prototype, "rotation", {
            /**
              * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z  (default is (0.0, 0.0, 0.0)).
              * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
              */
            get: function () {
                return this._rotation;
            },
            set: function (newRotation) {
                this._rotation = newRotation;
                this._isDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TransformNode.prototype, "scaling", {
            /**
             * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (0.0, 0.0, 0.0)).
             */
            get: function () {
                return this._scaling;
            },
            set: function (newScaling) {
                this._scaling = newScaling;
                this._isDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
            /**
             * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
             * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
             */
            get: function () {
                return this._rotationQuaternion;
            },
            set: function (quaternion) {
                this._rotationQuaternion = quaternion;
                //reset the rotation vector.
                if (quaternion && this.rotation.length()) {
                    this.rotation.copyFromFloats(0.0, 0.0, 0.0);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TransformNode.prototype, "forward", {
            /**
             * The forward direction of that transform in world space.
             */
            get: function () {
                return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TransformNode.prototype, "up", {
            /**
             * The up direction of that transform in world space.
             */
            get: function () {
                return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TransformNode.prototype, "right", {
            /**
             * The right direction of that transform in world space.
             */
            get: function () {
                return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Copies the parameter passed Matrix into the mesh Pose matrix.
         * @param matrix the matrix to copy the pose from
         * @returns this TransformNode.
         */
        TransformNode.prototype.updatePoseMatrix = function (matrix) {
            this._poseMatrix.copyFrom(matrix);
            return this;
        };
        /**
         * Returns the mesh Pose matrix.
         * @returns the pose matrix
         */
        TransformNode.prototype.getPoseMatrix = function () {
            return this._poseMatrix;
        };
        /** @hidden */
        TransformNode.prototype._isSynchronized = function () {
            if (this._isDirty) {
                return false;
            }
            if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
                return false;
            }
            if (this._cache.pivotMatrixUpdated) {
                return false;
            }
            if (this.infiniteDistance) {
                return false;
            }
            if (!this._cache.position.equals(this._position)) {
                return false;
            }
            if (this._rotationQuaternion) {
                if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion)) {
                    return false;
                }
            }
            if (!this._cache.rotation.equals(this._rotation)) {
                return false;
            }
            if (!this._cache.scaling.equals(this._scaling)) {
                return false;
            }
            return true;
        };
        /** @hidden */
        TransformNode.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.localMatrixUpdated = false;
            this._cache.position = BABYLON.Vector3.Zero();
            this._cache.scaling = BABYLON.Vector3.Zero();
            this._cache.rotation = BABYLON.Vector3.Zero();
            this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
            this._cache.billboardMode = -1;
        };
        /**
        * Flag the transform node as dirty (Forcing it to update everything)
        * @param property if set to "rotation" the objects rotationQuaternion will be set to null
        * @returns this transform node
        */
        TransformNode.prototype.markAsDirty = function (property) {
            if (property === "rotation") {
                this.rotationQuaternion = null;
            }
            this._currentRenderId = Number.MAX_VALUE;
            this._isDirty = true;
            return this;
        };
        Object.defineProperty(TransformNode.prototype, "absolutePosition", {
            /**
             * Returns the current mesh absolute position.
             * Returns a Vector3.
             */
            get: function () {
                return this._absolutePosition;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Sets a new matrix to apply before all other transformation
         * @param matrix defines the transform matrix
         * @returns the current TransformNode
         */
        TransformNode.prototype.setPreTransformMatrix = function (matrix) {
            return this.setPivotMatrix(matrix, false);
        };
        /**
         * Sets a new pivot matrix to the current node
         * @param matrix defines the new pivot matrix to use
         * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect
         * @returns the current TransformNode
        */
        TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
            if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
            this._pivotMatrix = matrix.clone();
            this._cache.pivotMatrixUpdated = true;
            this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
            if (this._postMultiplyPivotMatrix) {
                if (!this._pivotMatrixInverse) {
                    this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
                }
                else {
                    this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
                }
            }
            return this;
        };
        /**
         * Returns the mesh pivot matrix.
         * Default : Identity.
         * @returns the matrix
         */
        TransformNode.prototype.getPivotMatrix = function () {
            return this._pivotMatrix;
        };
        /**
         * Prevents the World matrix to be computed any longer.
         * @returns the TransformNode.
         */
        TransformNode.prototype.freezeWorldMatrix = function () {
            this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
            this.computeWorldMatrix(true);
            this._isWorldMatrixFrozen = true;
            return this;
        };
        /**
         * Allows back the World matrix computation.
         * @returns the TransformNode.
         */
        TransformNode.prototype.unfreezeWorldMatrix = function () {
            this._isWorldMatrixFrozen = false;
            this.computeWorldMatrix(true);
            return this;
        };
        Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
            /**
             * True if the World matrix has been frozen.
             */
            get: function () {
                return this._isWorldMatrixFrozen;
            },
            enumerable: true,
            configurable: true
        });
        /**
        * Retuns the mesh absolute position in the World.
        * @returns a Vector3.
        */
        TransformNode.prototype.getAbsolutePosition = function () {
            this.computeWorldMatrix();
            return this._absolutePosition;
        };
        /**
         * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
         * @param absolutePosition the absolute position to set
         * @returns the TransformNode.
         */
        TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
            if (!absolutePosition) {
                return this;
            }
            var absolutePositionX;
            var absolutePositionY;
            var absolutePositionZ;
            if (absolutePosition.x === undefined) {
                if (arguments.length < 3) {
                    return this;
                }
                absolutePositionX = arguments[0];
                absolutePositionY = arguments[1];
                absolutePositionZ = arguments[2];
            }
            else {
                absolutePositionX = absolutePosition.x;
                absolutePositionY = absolutePosition.y;
                absolutePositionZ = absolutePosition.z;
            }
            if (this.parent) {
                var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
                invertParentWorldMatrix.invert();
                var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
                this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
            }
            else {
                this.position.x = absolutePositionX;
                this.position.y = absolutePositionY;
                this.position.z = absolutePositionZ;
            }
            return this;
        };
        /**
         * Sets the mesh position in its local space.
         * @param vector3 the position to set in localspace
         * @returns the TransformNode.
         */
        TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
            this.computeWorldMatrix();
            this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
            return this;
        };
        /**
         * Returns the mesh position in the local space from the current World matrix values.
         * @returns a new Vector3.
         */
        TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
            this.computeWorldMatrix();
            var invLocalWorldMatrix = this._localWorld.clone();
            invLocalWorldMatrix.invert();
            return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
        };
        /**
         * Translates the mesh along the passed Vector3 in its local space.
         * @param vector3 the distance to translate in localspace
         * @returns the TransformNode.
         */
        TransformNode.prototype.locallyTranslate = function (vector3) {
            this.computeWorldMatrix(true);
            this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
            return this;
        };
        /**
         * Orients a mesh towards a target point. Mesh must be drawn facing user.
         * @param targetPoint the position (must be in same space as current mesh) to look at
         * @param yawCor optional yaw (y-axis) correction in radians
         * @param pitchCor optional pitch (x-axis) correction in radians
         * @param rollCor optional roll (z-axis) correction in radians
         * @param space the choosen space of the target
         * @returns the TransformNode.
         */
        TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
            if (yawCor === void 0) { yawCor = 0; }
            if (pitchCor === void 0) { pitchCor = 0; }
            if (rollCor === void 0) { rollCor = 0; }
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var dv = TransformNode._lookAtVectorCache;
            var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
            targetPoint.subtractToRef(pos, dv);
            var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
            var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
            var pitch = Math.atan2(dv.y, len);
            if (this.rotationQuaternion) {
                BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
            }
            else {
                this.rotation.x = pitch + pitchCor;
                this.rotation.y = yaw + yawCor;
                this.rotation.z = rollCor;
            }
            return this;
        };
        /**
          * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
          * This Vector3 is expressed in the World space.
          * @param localAxis axis to rotate
          * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
          */
        TransformNode.prototype.getDirection = function (localAxis) {
            var result = BABYLON.Vector3.Zero();
            this.getDirectionToRef(localAxis, result);
            return result;
        };
        /**
         * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
         * localAxis is expressed in the mesh local space.
         * result is computed in the Wordl space from the mesh World matrix.
         * @param localAxis axis to rotate
         * @param result the resulting transformnode
         * @returns this TransformNode.
         */
        TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
            BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
            return this;
        };
        /**
         * Sets a new pivot point to the current node
         * @param point defines the new pivot point to use
         * @param space defines if the point is in world or local space (local by default)
         * @returns the current TransformNode
        */
        TransformNode.prototype.setPivotPoint = function (point, space) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (this.getScene().getRenderId() == 0) {
                this.computeWorldMatrix(true);
            }
            var wm = this.getWorldMatrix();
            if (space == BABYLON.Space.WORLD) {
                var tmat = BABYLON.Tmp.Matrix[0];
                wm.invertToRef(tmat);
                point = BABYLON.Vector3.TransformCoordinates(point, tmat);
            }
            return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
        };
        /**
         * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
         * @returns the pivot point
         */
        TransformNode.prototype.getPivotPoint = function () {
            var point = BABYLON.Vector3.Zero();
            this.getPivotPointToRef(point);
            return point;
        };
        /**
         * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
         * @param result the vector3 to store the result
         * @returns this TransformNode.
         */
        TransformNode.prototype.getPivotPointToRef = function (result) {
            result.x = -this._pivotMatrix.m[12];
            result.y = -this._pivotMatrix.m[13];
            result.z = -this._pivotMatrix.m[14];
            return this;
        };
        /**
         * Returns a new Vector3 set with the mesh pivot point World coordinates.
         * @returns a new Vector3 set with the mesh pivot point World coordinates.
         */
        TransformNode.prototype.getAbsolutePivotPoint = function () {
            var point = BABYLON.Vector3.Zero();
            this.getAbsolutePivotPointToRef(point);
            return point;
        };
        /**
         * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
         * @param result vector3 to store the result
         * @returns this TransformNode.
         */
        TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
            result.x = this._pivotMatrix.m[12];
            result.y = this._pivotMatrix.m[13];
            result.z = this._pivotMatrix.m[14];
            this.getPivotPointToRef(result);
            BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
            return this;
        };
        /**
         * Defines the passed node as the parent of the current node.
         * The node will remain exactly where it is and its position / rotation will be updated accordingly
         * @param node the node ot set as the parent
         * @returns this TransformNode.
         */
        TransformNode.prototype.setParent = function (node) {
            if (!node && !this.parent) {
                return this;
            }
            if (!node) {
                var rotation = BABYLON.Tmp.Quaternion[0];
                var position = BABYLON.Tmp.Vector3[0];
                var scale = BABYLON.Tmp.Vector3[1];
                if (this.parent && this.parent.computeWorldMatrix) {
                    this.parent.computeWorldMatrix(true);
                }
                this.computeWorldMatrix(true);
                this.getWorldMatrix().decompose(scale, rotation, position);
                if (this.rotationQuaternion) {
                    this.rotationQuaternion.copyFrom(rotation);
                }
                else {
                    rotation.toEulerAnglesToRef(this.rotation);
                }
                this.scaling.x = scale.x;
                this.scaling.y = scale.y;
                this.scaling.z = scale.z;
                this.position.x = position.x;
                this.position.y = position.y;
                this.position.z = position.z;
            }
            else {
                var rotation = BABYLON.Tmp.Quaternion[0];
                var position = BABYLON.Tmp.Vector3[0];
                var scale = BABYLON.Tmp.Vector3[1];
                var diffMatrix = BABYLON.Tmp.Matrix[0];
                var invParentMatrix = BABYLON.Tmp.Matrix[1];
                this.computeWorldMatrix(true);
                node.computeWorldMatrix(true);
                node.getWorldMatrix().invertToRef(invParentMatrix);
                this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
                diffMatrix.decompose(scale, rotation, position);
                if (this.rotationQuaternion) {
                    this.rotationQuaternion.copyFrom(rotation);
                }
                else {
                    rotation.toEulerAnglesToRef(this.rotation);
                }
                this.position.x = position.x;
                this.position.y = position.y;
                this.position.z = position.z;
                this.scaling.x = scale.x;
                this.scaling.y = scale.y;
                this.scaling.z = scale.z;
            }
            this.parent = node;
            return this;
        };
        Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
            /**
             * True if the scaling property of this object is non uniform eg. (1,2,1)
             */
            get: function () {
                return this._nonUniformScaling;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        TransformNode.prototype._updateNonUniformScalingState = function (value) {
            if (this._nonUniformScaling === value) {
                return false;
            }
            this._nonUniformScaling = value;
            return true;
        };
        /**
         * Attach the current TransformNode to another TransformNode associated with a bone
         * @param bone Bone affecting the TransformNode
         * @param affectedTransformNode TransformNode associated with the bone
         * @returns this object
         */
        TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
            this._transformToBoneReferal = affectedTransformNode;
            this.parent = bone;
            if (bone.getWorldMatrix().determinant() < 0) {
                this.scalingDeterminant *= -1;
            }
            return this;
        };
        /**
         * Detach the transform node if its associated with a bone
         * @returns this object
         */
        TransformNode.prototype.detachFromBone = function () {
            if (!this.parent) {
                return this;
            }
            if (this.parent.getWorldMatrix().determinant() < 0) {
                this.scalingDeterminant *= -1;
            }
            this._transformToBoneReferal = null;
            this.parent = null;
            return this;
        };
        /**
         * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
         * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
         * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
         * The passed axis is also normalized.
         * @param axis the axis to rotate around
         * @param amount the amount to rotate in radians
         * @param space Space to rotate in (Default: local)
         * @returns the TransformNode.
         */
        TransformNode.prototype.rotate = function (axis, amount, space) {
            axis.normalize();
            if (!this.rotationQuaternion) {
                this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
                this.rotation = BABYLON.Vector3.Zero();
            }
            var rotationQuaternion;
            if (!space || space === BABYLON.Space.LOCAL) {
                rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
                this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
            }
            else {
                if (this.parent) {
                    var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
                    invertParentWorldMatrix.invert();
                    axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
                }
                rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
                rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
            }
            return this;
        };
        /**
         * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
         * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
         * The passed axis is also normalized. .
         * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
         * @param point the point to rotate around
         * @param axis the axis to rotate around
         * @param amount the amount to rotate in radians
         * @returns the TransformNode
         */
        TransformNode.prototype.rotateAround = function (point, axis, amount) {
            axis.normalize();
            if (!this.rotationQuaternion) {
                this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
                this.rotation.copyFromFloats(0, 0, 0);
            }
            point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
            BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
            BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
            BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
            BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
            BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
            BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
            this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
            BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
            return this;
        };
        /**
         * Translates the mesh along the axis vector for the passed distance in the given space.
         * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
         * @param axis the axis to translate in
         * @param distance the distance to translate
         * @param space Space to rotate in (Default: local)
         * @returns the TransformNode.
         */
        TransformNode.prototype.translate = function (axis, distance, space) {
            var displacementVector = axis.scale(distance);
            if (!space || space === BABYLON.Space.LOCAL) {
                var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
                this.setPositionWithLocalVector(tempV3);
            }
            else {
                this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
            }
            return this;
        };
        /**
         * Adds a rotation step to the mesh current rotation.
         * x, y, z are Euler angles expressed in radians.
         * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
         * This means this rotation is made in the mesh local space only.
         * It's useful to set a custom rotation order different from the BJS standard one YXZ.
         * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
         * ```javascript
         * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
         * ```
         * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
         * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
         * @param x Rotation to add
         * @param y Rotation to add
         * @param z Rotation to add
         * @returns the TransformNode.
         */
        TransformNode.prototype.addRotation = function (x, y, z) {
            var rotationQuaternion;
            if (this.rotationQuaternion) {
                rotationQuaternion = this.rotationQuaternion;
            }
            else {
                rotationQuaternion = BABYLON.Tmp.Quaternion[1];
                BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
            }
            var accumulation = BABYLON.Tmp.Quaternion[0];
            BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
            rotationQuaternion.multiplyInPlace(accumulation);
            if (!this.rotationQuaternion) {
                rotationQuaternion.toEulerAnglesToRef(this.rotation);
            }
            return this;
        };
        /**
         * Computes the world matrix of the node
         * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
         * @returns the world matrix
         */
        TransformNode.prototype.computeWorldMatrix = function (force) {
            if (this._isWorldMatrixFrozen) {
                return this._worldMatrix;
            }
            if (!force && this.isSynchronized()) {
                this._currentRenderId = this.getScene().getRenderId();
                return this._worldMatrix;
            }
            this._updateCache();
            this._cache.position.copyFrom(this.position);
            this._cache.scaling.copyFrom(this.scaling);
            this._cache.pivotMatrixUpdated = false;
            this._cache.billboardMode = this.billboardMode;
            this._currentRenderId = this.getScene().getRenderId();
            this._childRenderId = this.getScene().getRenderId();
            this._isDirty = false;
            // Scaling
            BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
            // Rotation
            //rotate, if quaternion is set and rotation was used
            if (this.rotationQuaternion) {
                var len = this.rotation.length();
                if (len) {
                    this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
                    this.rotation.copyFromFloats(0, 0, 0);
                }
            }
            if (this.rotationQuaternion) {
                this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
                this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
            }
            else {
                BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
                this._cache.rotation.copyFrom(this.rotation);
            }
            // Translation
            var camera = this.getScene().activeCamera;
            if (this.infiniteDistance && !this.parent && camera) {
                var cameraWorldMatrix = camera.getWorldMatrix();
                var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
                BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
            }
            else {
                BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
            }
            // Composing transformations
            this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
            BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
            // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
            if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
                if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
                    // Need to decompose each rotation here
                    var currentPosition = BABYLON.Tmp.Vector3[3];
                    if (this.parent && this.parent.getWorldMatrix) {
                        if (this._transformToBoneReferal) {
                            this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
                            BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
                        }
                        else {
                            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
                        }
                    }
                    else {
                        currentPosition.copyFrom(this.position);
                    }
                    currentPosition.subtractInPlace(camera.globalPosition);
                    var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
                    if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
                        finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
                    }
                    if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
                        finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
                    }
                    if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
                        finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
                    }
                    BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
                }
                else {
                    BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
                    BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
                    BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
                }
                BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
                BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
            }
            // Post multiply inverse of pivotMatrix
            if (this._postMultiplyPivotMatrix) {
                BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
            }
            // Local world
            BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
            // Parent
            if (this.parent && this.parent.getWorldMatrix) {
                if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
                    if (this._transformToBoneReferal) {
                        this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
                        BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
                    }
                    else {
                        BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
                    }
                    this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
                    BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
                    this._worldMatrix.copyFrom(this._localWorld);
                    this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
                }
                else {
                    if (this._transformToBoneReferal) {
                        this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
                        BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
                    }
                    else {
                        this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
                    }
                }
                this._markSyncedWithParent();
            }
            else {
                this._worldMatrix.copyFrom(this._localWorld);
            }
            // Normal matrix
            if (!this.ignoreNonUniformScaling) {
                if (this.scaling.isNonUniform) {
                    this._updateNonUniformScalingState(true);
                }
                else if (this.parent && this.parent._nonUniformScaling) {
                    this._updateNonUniformScalingState(this.parent._nonUniformScaling);
                }
                else {
                    this._updateNonUniformScalingState(false);
                }
            }
            else {
                this._updateNonUniformScalingState(false);
            }
            this._afterComputeWorldMatrix();
            // Absolute position
            this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
            // Callbacks
            this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
            if (!this._poseMatrix) {
                this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
            }
            // Cache the determinant
            this._worldMatrixDeterminant = this._worldMatrix.determinant();
            return this._worldMatrix;
        };
        TransformNode.prototype._afterComputeWorldMatrix = function () {
        };
        /**
        * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
        * @param func callback function to add
        *
        * @returns the TransformNode.
        */
        TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
            this.onAfterWorldMatrixUpdateObservable.add(func);
            return this;
        };
        /**
         * Removes a registered callback function.
         * @param func callback function to remove
         * @returns the TransformNode.
         */
        TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
            this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
            return this;
        };
        /**
         * Clone the current transform node
         * @param name Name of the new clone
         * @param newParent New parent for the clone
         * @param doNotCloneChildren Do not clone children hierarchy
         * @returns the new transform node
         */
        TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
            var _this = this;
            var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
            result.name = name;
            result.id = name;
            if (newParent) {
                result.parent = newParent;
            }
            if (!doNotCloneChildren) {
                // Children
                var directDescendants = this.getDescendants(true);
                for (var index = 0; index < directDescendants.length; index++) {
                    var child = directDescendants[index];
                    if (child.clone) {
                        child.clone(name + "." + child.name, result);
                    }
                }
            }
            return result;
        };
        /**
         * Serializes the objects information.
         * @param currentSerializationObject defines the object to serialize in
         * @returns the serialized object
         */
        TransformNode.prototype.serialize = function (currentSerializationObject) {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
            serializationObject.type = this.getClassName();
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
                serializationObject.tags = BABYLON.Tags.GetTags(this);
            }
            serializationObject.localMatrix = this.getPivotMatrix().asArray();
            serializationObject.isEnabled = this.isEnabled();
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            return serializationObject;
        };
        // Statics
        /**
         * Returns a new TransformNode object parsed from the source provided.
         * @param parsedTransformNode is the source.
         * @param scene the scne the object belongs to
         * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
         * @returns a new TransformNode object parsed from the source provided.
         */
        TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
            var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
            }
            if (parsedTransformNode.localMatrix) {
                transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
            }
            else if (parsedTransformNode.pivotMatrix) {
                transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
            }
            transformNode.setEnabled(parsedTransformNode.isEnabled);
            // Parent
            if (parsedTransformNode.parentId) {
                transformNode._waitingParentId = parsedTransformNode.parentId;
            }
            return transformNode;
        };
        /**
         * Releases resources associated with this transform node.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            this.getScene().removeTransformNode(this);
            this.onAfterWorldMatrixUpdateObservable.clear();
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        // Statics
        /**
         * Object will not rotate to face the camera
         */
        TransformNode.BILLBOARDMODE_NONE = 0;
        /**
         * Object will rotate to face the camera but only on the x axis
         */
        TransformNode.BILLBOARDMODE_X = 1;
        /**
         * Object will rotate to face the camera but only on the y axis
         */
        TransformNode.BILLBOARDMODE_Y = 2;
        /**
         * Object will rotate to face the camera but only on the z axis
         */
        TransformNode.BILLBOARDMODE_Z = 4;
        /**
         * Object will rotate to face the camera
         */
        TransformNode.BILLBOARDMODE_ALL = 7;
        TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
        TransformNode._rotationAxisCache = new BABYLON.Quaternion();
        __decorate([
            BABYLON.serializeAsVector3("position")
        ], TransformNode.prototype, "_position", void 0);
        __decorate([
            BABYLON.serializeAsVector3("rotation")
        ], TransformNode.prototype, "_rotation", void 0);
        __decorate([
            BABYLON.serializeAsQuaternion("rotationQuaternion")
        ], TransformNode.prototype, "_rotationQuaternion", void 0);
        __decorate([
            BABYLON.serializeAsVector3("scaling")
        ], TransformNode.prototype, "_scaling", void 0);
        __decorate([
            BABYLON.serialize()
        ], TransformNode.prototype, "billboardMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], TransformNode.prototype, "scalingDeterminant", void 0);
        __decorate([
            BABYLON.serialize()
        ], TransformNode.prototype, "infiniteDistance", void 0);
        __decorate([
            BABYLON.serialize()
        ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
        return TransformNode;
    }(BABYLON.Node));
    BABYLON.TransformNode = TransformNode;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.transformNode.js.map


var BABYLON;
(function (BABYLON) {
    /** @hidden */
    var _FacetDataStorage = /** @class */ (function () {
        function _FacetDataStorage() {
            this.facetNb = 0; // facet number
            this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
            this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
            this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
            this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
            this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
            this.subDiv = {
                max: 1,
                X: 1,
                Y: 1,
                Z: 1
            };
            this.facetDepthSort = false; // is the facet depth sort to be computed
            this.facetDepthSortEnabled = false; // is the facet depth sort initialized
        }
        return _FacetDataStorage;
    }());
    /**
     * Class used to store all common mesh properties
     */
    var AbstractMesh = /** @class */ (function (_super) {
        __extends(AbstractMesh, _super);
        // Constructor
        /**
         * Creates a new AbstractMesh
         * @param name defines the name of the mesh
         * @param scene defines the hosting scene
         */
        function AbstractMesh(name, scene) {
            if (scene === void 0) { scene = null; }
            var _this = _super.call(this, name, scene, false) || this;
            _this._facetData = new _FacetDataStorage();
            /** Gets ot sets the culling strategy to use to find visible meshes */
            _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
            // Events
            /**
            * An event triggered when this mesh collides with another one
            */
            _this.onCollideObservable = new BABYLON.Observable();
            /**
            * An event triggered when the collision's position changes
            */
            _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
            /**
            * An event triggered when material is changed
            */
            _this.onMaterialChangedObservable = new BABYLON.Observable();
            // Properties
            /**
             * Gets or sets the orientation for POV movement & rotation
             */
            _this.definedFacingForward = true;
            _this._visibility = 1.0;
            /** Gets or sets the alpha index used to sort transparent meshes
             * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
             */
            _this.alphaIndex = Number.MAX_VALUE;
            /**
             * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
             */
            _this.isVisible = true;
            /**
             * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
             */
            _this.isPickable = true;
            /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
            _this.showSubMeshesBoundingBox = false;
            /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
             * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
             */
            _this.isBlocker = false;
            /**
             * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
             */
            _this.enablePointerMoveEvents = false;
            /**
             * Specifies the rendering group id for this mesh (0 by default)
             * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
             */
            _this.renderingGroupId = 0;
            _this._receiveShadows = false;
            /** Defines color to use when rendering outline */
            _this.outlineColor = BABYLON.Color3.Red();
            /** Define width to use when rendering outline */
            _this.outlineWidth = 0.02;
            /** Defines color to use when rendering overlay */
            _this.overlayColor = BABYLON.Color3.Red();
            /** Defines alpha to use when rendering overlay */
            _this.overlayAlpha = 0.5;
            _this._hasVertexAlpha = false;
            _this._useVertexColors = true;
            _this._computeBonesUsingShaders = true;
            _this._numBoneInfluencers = 4;
            _this._applyFog = true;
            /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
            _this.useOctreeForRenderingSelection = true;
            /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
            _this.useOctreeForPicking = true;
            /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
            _this.useOctreeForCollisions = true;
            _this._layerMask = 0x0FFFFFFF;
            /**
             * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
             */
            _this.alwaysSelectAsActiveMesh = false;
            /**
             * Gets or sets the current action manager
             * @see http://doc.babylonjs.com/how_to/how_to_use_actions
             */
            _this.actionManager = null;
            // Collisions
            _this._checkCollisions = false;
            _this._collisionMask = -1;
            _this._collisionGroup = -1;
            /**
             * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
             */
            _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
            /**
             * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
             */
            _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
            _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
            _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
            // Edges
            /**
             * Defines edge width used when edgesRenderer is enabled
             * @see https://www.babylonjs-playground.com/#10OJSG#13
             */
            _this.edgesWidth = 1;
            /**
             * Defines edge color used when edgesRenderer is enabled
             * @see https://www.babylonjs-playground.com/#10OJSG#13
             */
            _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
            /** @hidden */
            _this._renderId = 0;
            /** @hidden */
            _this._intersectionsInProgress = new Array();
            /** @hidden */
            _this._unIndexed = false;
            /** @hidden */
            _this._lightSources = new Array();
            /**
             * An event triggered when the mesh is rebuilt.
             */
            _this.onRebuildObservable = new BABYLON.Observable();
            _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
                if (collidedMesh === void 0) { collidedMesh = null; }
                //TODO move this to the collision coordinator!
                if (_this.getScene().workerCollisions) {
                    newPosition.multiplyInPlace(_this._collider._radius);
                }
                newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
                if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
                    _this.position.addInPlace(_this._diffPositionForCollisions);
                }
                if (collidedMesh) {
                    _this.onCollideObservable.notifyObservers(collidedMesh);
                }
                _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
            };
            _this.getScene().addMesh(_this);
            _this._resyncLightSources();
            return _this;
        }
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
            /**
             * No billboard
             */
            get: function () {
                return BABYLON.TransformNode.BILLBOARDMODE_NONE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
            /** Billboard on X axis */
            get: function () {
                return BABYLON.TransformNode.BILLBOARDMODE_X;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
            /** Billboard on Y axis */
            get: function () {
                return BABYLON.TransformNode.BILLBOARDMODE_Y;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
            /** Billboard on Z axis */
            get: function () {
                return BABYLON.TransformNode.BILLBOARDMODE_Z;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
            /** Billboard on all axes */
            get: function () {
                return BABYLON.TransformNode.BILLBOARDMODE_ALL;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "facetNb", {
            /**
             * Gets the number of facets in the mesh
             * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
             */
            get: function () {
                return this._facetData.facetNb;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
            /**
             * Gets or set the number (integer) of subdivisions per axis in the partioning space
             * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
             */
            get: function () {
                return this._facetData.partitioningSubdivisions;
            },
            set: function (nb) {
                this._facetData.partitioningSubdivisions = nb;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
            /**
             * The ratio (float) to apply to the bouding box size to set to the partioning space.
             * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
             * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
             */
            get: function () {
                return this._facetData.partitioningBBoxRatio;
            },
            set: function (ratio) {
                this._facetData.partitioningBBoxRatio = ratio;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
            /**
             * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
             * Works only for updatable meshes.
             * Doesn't work with multi-materials
             * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
             */
            get: function () {
                return this._facetData.facetDepthSort;
            },
            set: function (sort) {
                this._facetData.facetDepthSort = sort;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
            /**
             * The location (Vector3) where the facet depth sort must be computed from.
             * By default, the active camera position.
             * Used only when facet depth sort is enabled
             * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
             */
            get: function () {
                return this._facetData.facetDepthSortFrom;
            },
            set: function (location) {
                this._facetData.facetDepthSortFrom = location;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
            /**
             * gets a boolean indicating if facetData is enabled
             * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
             */
            get: function () {
                return this._facetData.facetDataEnabled;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
            if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
                return false;
            }
            this._markSubMeshesAsMiscDirty();
            return true;
        };
        Object.defineProperty(AbstractMesh.prototype, "onCollide", {
            /** Set a function to call when this mesh collides with another one */
            set: function (callback) {
                if (this._onCollideObserver) {
                    this.onCollideObservable.remove(this._onCollideObserver);
                }
                this._onCollideObserver = this.onCollideObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
            /** Set a function to call when the collision's position changes */
            set: function (callback) {
                if (this._onCollisionPositionChangeObserver) {
                    this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
                }
                this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "visibility", {
            /**
             * Gets or sets mesh visibility between 0 and 1 (default is 1)
             */
            get: function () {
                return this._visibility;
            },
            /**
             * Gets or sets mesh visibility between 0 and 1 (default is 1)
             */
            set: function (value) {
                if (this._visibility === value) {
                    return;
                }
                this._visibility = value;
                this._markSubMeshesAsMiscDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "material", {
            /** Gets or sets current material */
            get: function () {
                return this._material;
            },
            set: function (value) {
                if (this._material === value) {
                    return;
                }
                this._material = value;
                if (this.onMaterialChangedObservable.hasObservers) {
                    this.onMaterialChangedObservable.notifyObservers(this);
                }
                if (!this.subMeshes) {
                    return;
                }
                this._unBindEffect();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
            /**
             * Gets or sets a boolean indicating that this mesh can receive realtime shadows
             * @see http://doc.babylonjs.com/babylon101/shadows
             */
            get: function () {
                return this._receiveShadows;
            },
            set: function (value) {
                if (this._receiveShadows === value) {
                    return;
                }
                this._receiveShadows = value;
                this._markSubMeshesAsLightDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
            /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
            get: function () {
                return this._hasVertexAlpha;
            },
            set: function (value) {
                if (this._hasVertexAlpha === value) {
                    return;
                }
                this._hasVertexAlpha = value;
                this._markSubMeshesAsAttributesDirty();
                this._markSubMeshesAsMiscDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
            /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
            get: function () {
                return this._useVertexColors;
            },
            set: function (value) {
                if (this._useVertexColors === value) {
                    return;
                }
                this._useVertexColors = value;
                this._markSubMeshesAsAttributesDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
            /**
             * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
             */
            get: function () {
                return this._computeBonesUsingShaders;
            },
            set: function (value) {
                if (this._computeBonesUsingShaders === value) {
                    return;
                }
                this._computeBonesUsingShaders = value;
                this._markSubMeshesAsAttributesDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
            /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
            get: function () {
                return this._numBoneInfluencers;
            },
            set: function (value) {
                if (this._numBoneInfluencers === value) {
                    return;
                }
                this._numBoneInfluencers = value;
                this._markSubMeshesAsAttributesDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "applyFog", {
            /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
            get: function () {
                return this._applyFog;
            },
            set: function (value) {
                if (this._applyFog === value) {
                    return;
                }
                this._applyFog = value;
                this._markSubMeshesAsMiscDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "layerMask", {
            /**
             * Gets or sets the current layer mask (default is 0x0FFFFFFF)
             * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
             */
            get: function () {
                return this._layerMask;
            },
            set: function (value) {
                if (value === this._layerMask) {
                    return;
                }
                this._layerMask = value;
                this._resyncLightSources();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
            /**
             * Gets or sets a collision mask used to mask collisions (default is -1).
             * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
             */
            get: function () {
                return this._collisionMask;
            },
            set: function (mask) {
                this._collisionMask = !isNaN(mask) ? mask : -1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
            /**
             * Gets or sets the current collision group mask (-1 by default).
             * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
             */
            get: function () {
                return this._collisionGroup;
            },
            set: function (mask) {
                this._collisionGroup = !isNaN(mask) ? mask : -1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "_positions", {
            /** @hidden */
            get: function () {
                return null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "skeleton", {
            get: function () {
                return this._skeleton;
            },
            /**
             * Gets or sets a skeleton to apply skining transformations
             * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
             */
            set: function (value) {
                if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
                    this._skeleton._unregisterMeshWithPoseMatrix(this);
                }
                if (value && value.needInitialSkinMatrix) {
                    value._registerMeshWithPoseMatrix(this);
                }
                this._skeleton = value;
                if (!this._skeleton) {
                    this._bonesTransformMatrices = null;
                }
                this._markSubMeshesAsAttributesDirty();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "AbstractMesh"
         * @returns "AbstractMesh"
         */
        AbstractMesh.prototype.getClassName = function () {
            return "AbstractMesh";
        };
        /**
         * Gets a string representation of the current mesh
         * @param fullDetails defines a boolean indicating if full details must be included
         * @returns a string representation of the current mesh
         */
        AbstractMesh.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
            ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
            if (this._skeleton) {
                ret += ", skeleton: " + this._skeleton.name;
            }
            if (fullDetails) {
                ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
                ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
            }
            return ret;
        };
        /** @hidden */
        AbstractMesh.prototype._rebuild = function () {
            this.onRebuildObservable.notifyObservers(this);
            if (this._occlusionQuery) {
                this._occlusionQuery = null;
            }
            if (!this.subMeshes) {
                return;
            }
            for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
                var subMesh = _a[_i];
                subMesh._rebuild();
            }
        };
        /** @hidden */
        AbstractMesh.prototype._resyncLightSources = function () {
            this._lightSources.length = 0;
            for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
                var light = _a[_i];
                if (!light.isEnabled()) {
                    continue;
                }
                if (light.canAffectMesh(this)) {
                    this._lightSources.push(light);
                }
            }
            this._markSubMeshesAsLightDirty();
        };
        /** @hidden */
        AbstractMesh.prototype._resyncLighSource = function (light) {
            var isIn = light.isEnabled() && light.canAffectMesh(this);
            var index = this._lightSources.indexOf(light);
            if (index === -1) {
                if (!isIn) {
                    return;
                }
                this._lightSources.push(light);
            }
            else {
                if (isIn) {
                    return;
                }
                this._lightSources.splice(index, 1);
            }
            this._markSubMeshesAsLightDirty();
        };
        /** @hidden */
        AbstractMesh.prototype._unBindEffect = function () {
            for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
                var subMesh = _a[_i];
                subMesh.setEffect(null);
            }
        };
        /** @hidden */
        AbstractMesh.prototype._removeLightSource = function (light) {
            var index = this._lightSources.indexOf(light);
            if (index === -1) {
                return;
            }
            this._lightSources.splice(index, 1);
            this._markSubMeshesAsLightDirty();
        };
        AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
            if (!this.subMeshes) {
                return;
            }
            for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
                var subMesh = _a[_i];
                if (subMesh._materialDefines) {
                    func(subMesh._materialDefines);
                }
            }
        };
        /** @hidden */
        AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
            this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
        };
        /** @hidden */
        AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
            this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
        };
        /** @hidden */
        AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
            if (!this.subMeshes) {
                return;
            }
            for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
                var subMesh = _a[_i];
                var material = subMesh.getMaterial();
                if (material) {
                    material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
                }
            }
        };
        Object.defineProperty(AbstractMesh.prototype, "scaling", {
            /**
            * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z.  Default is (1.0, 1.0, 1.0)
            */
            get: function () {
                return this._scaling;
            },
            set: function (newScaling) {
                this._scaling = newScaling;
                if (this.physicsImpostor) {
                    this.physicsImpostor.forceUpdate();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
            // Methods
            /**
             * Returns true if the mesh is blocked. Implemented by child classes
             */
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the mesh itself by default. Implemented by child classes
         * @param camera defines the camera to use to pick the right LOD level
         * @returns the currentAbstractMesh
         */
        AbstractMesh.prototype.getLOD = function (camera) {
            return this;
        };
        /**
         * Returns 0 by default. Implemented by child classes
         * @returns an integer
         */
        AbstractMesh.prototype.getTotalVertices = function () {
            return 0;
        };
        /**
         * Returns null by default. Implemented by child classes
         * @returns null
         */
        AbstractMesh.prototype.getIndices = function () {
            return null;
        };
        /**
         * Returns the array of the requested vertex data kind. Implemented by child classes
         * @param kind defines the vertex data kind to use
         * @returns null
         */
        AbstractMesh.prototype.getVerticesData = function (kind) {
            return null;
        };
        /**
         * Sets the vertex data of the mesh geometry for the requested `kind`.
         * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
         * Note that a new underlying VertexBuffer object is created each call.
         * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
         * @param kind defines vertex data kind:
         * * BABYLON.VertexBuffer.PositionKind
         * * BABYLON.VertexBuffer.UVKind
         * * BABYLON.VertexBuffer.UV2Kind
         * * BABYLON.VertexBuffer.UV3Kind
         * * BABYLON.VertexBuffer.UV4Kind
         * * BABYLON.VertexBuffer.UV5Kind
         * * BABYLON.VertexBuffer.UV6Kind
         * * BABYLON.VertexBuffer.ColorKind
         * * BABYLON.VertexBuffer.MatricesIndicesKind
         * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * * BABYLON.VertexBuffer.MatricesWeightsKind
         * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @param data defines the data source
         * @param updatable defines if the data must be flagged as updatable (or static)
         * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
         * @returns the current mesh
         */
        AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
            return this;
        };
        /**
         * Updates the existing vertex data of the mesh geometry for the requested `kind`.
         * If the mesh has no geometry, it is simply returned as it is.
         * @param kind defines vertex data kind:
         * * BABYLON.VertexBuffer.PositionKind
         * * BABYLON.VertexBuffer.UVKind
         * * BABYLON.VertexBuffer.UV2Kind
         * * BABYLON.VertexBuffer.UV3Kind
         * * BABYLON.VertexBuffer.UV4Kind
         * * BABYLON.VertexBuffer.UV5Kind
         * * BABYLON.VertexBuffer.UV6Kind
         * * BABYLON.VertexBuffer.ColorKind
         * * BABYLON.VertexBuffer.MatricesIndicesKind
         * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * * BABYLON.VertexBuffer.MatricesWeightsKind
         * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @param data defines the data source
         * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
         * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
         * @returns the current mesh
         */
        AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
            return this;
        };
        /**
         * Sets the mesh indices,
         * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
         * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
         * @param totalVertices Defines the total number of vertices
         * @returns the current mesh
         */
        AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
            return this;
        };
        /**
         * Gets a boolean indicating if specific vertex data is present
         * @param kind defines the vertex data kind to use
         * @returns true is data kind is present
         */
        AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
            return false;
        };
        /**
         * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
         * @returns a BoundingInfo
         */
        AbstractMesh.prototype.getBoundingInfo = function () {
            if (this._masterMesh) {
                return this._masterMesh.getBoundingInfo();
            }
            if (!this._boundingInfo) {
                // this._boundingInfo is being created here
                this._updateBoundingInfo();
            }
            // cannot be null.
            return this._boundingInfo;
        };
        /**
         * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
         * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
         * @returns the current mesh
         */
        AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
            if (includeDescendants === void 0) { includeDescendants = true; }
            var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
            var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
            var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
            if (maxDimension === 0) {
                return this;
            }
            var scale = 1 / maxDimension;
            this.scaling.scaleInPlace(scale);
            return this;
        };
        /**
         * Overwrite the current bounding info
         * @param boundingInfo defines the new bounding info
         * @returns the current mesh
         */
        AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
            this._boundingInfo = boundingInfo;
            return this;
        };
        Object.defineProperty(AbstractMesh.prototype, "useBones", {
            /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
            get: function () {
                return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        AbstractMesh.prototype._preActivate = function () {
        };
        /** @hidden */
        AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
        };
        /** @hidden */
        AbstractMesh.prototype._activate = function (renderId) {
            this._renderId = renderId;
        };
        /**
         * Gets the current world matrix
         * @returns a Matrix
         */
        AbstractMesh.prototype.getWorldMatrix = function () {
            if (this._masterMesh) {
                return this._masterMesh.getWorldMatrix();
            }
            return _super.prototype.getWorldMatrix.call(this);
        };
        /** @hidden */
        AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
            if (this._masterMesh) {
                return this._masterMesh._getWorldMatrixDeterminant();
            }
            return _super.prototype._getWorldMatrixDeterminant.call(this);
        };
        // ================================== Point of View Movement =================================
        /**
         * Perform relative position change from the point of view of behind the front of the mesh.
         * This is performed taking into account the meshes current rotation, so you do not have to care.
         * Supports definition of mesh facing forward or backward
         * @param amountRight defines the distance on the right axis
         * @param amountUp defines the distance on the up axis
         * @param amountForward defines the distance on the forward axis
         * @returns the current mesh
         */
        AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
            this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
            return this;
        };
        /**
         * Calculate relative position change from the point of view of behind the front of the mesh.
         * This is performed taking into account the meshes current rotation, so you do not have to care.
         * Supports definition of mesh facing forward or backward
         * @param amountRight defines the distance on the right axis
         * @param amountUp defines the distance on the up axis
         * @param amountForward defines the distance on the forward axis
         * @returns the new displacement vector
         */
        AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
            var rotMatrix = new BABYLON.Matrix();
            var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
            rotQuaternion.toRotationMatrix(rotMatrix);
            var translationDelta = BABYLON.Vector3.Zero();
            var defForwardMult = this.definedFacingForward ? -1 : 1;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
            return translationDelta;
        };
        // ================================== Point of View Rotation =================================
        /**
         * Perform relative rotation change from the point of view of behind the front of the mesh.
         * Supports definition of mesh facing forward or backward
         * @param flipBack defines the flip
         * @param twirlClockwise defines the twirl
         * @param tiltRight defines the tilt
         * @returns the current mesh
         */
        AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
            this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
            return this;
        };
        /**
         * Calculate relative rotation change from the point of view of behind the front of the mesh.
         * Supports definition of mesh facing forward or backward.
         * @param flipBack defines the flip
         * @param twirlClockwise defines the twirl
         * @param tiltRight defines the tilt
         * @returns the new rotation vector
         */
        AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
            var defForwardMult = this.definedFacingForward ? 1 : -1;
            return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
        };
        /**
         * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
         * @param includeDescendants Include bounding info from descendants as well (true by default)
         * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
         * @returns the new bounding vectors
         */
        AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
            if (includeDescendants === void 0) { includeDescendants = true; }
            if (predicate === void 0) { predicate = null; }
            // Ensures that all world matrix will be recomputed.
            this.getScene().incrementRenderId();
            this.computeWorldMatrix(true);
            var min;
            var max;
            var boundingInfo = this.getBoundingInfo();
            if (!this.subMeshes) {
                min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
                max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            }
            else {
                min = boundingInfo.boundingBox.minimumWorld;
                max = boundingInfo.boundingBox.maximumWorld;
            }
            if (includeDescendants) {
                var descendants = this.getDescendants(false);
                for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
                    var descendant = descendants_1[_i];
                    var childMesh = descendant;
                    childMesh.computeWorldMatrix(true);
                    // Filters meshes based on custom predicate function.
                    if (predicate && !predicate(childMesh)) {
                        continue;
                    }
                    //make sure we have the needed params to get mix and max
                    if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
                        continue;
                    }
                    var childBoundingInfo = childMesh.getBoundingInfo();
                    var boundingBox = childBoundingInfo.boundingBox;
                    var minBox = boundingBox.minimumWorld;
                    var maxBox = boundingBox.maximumWorld;
                    BABYLON.Tools.CheckExtends(minBox, min, max);
                    BABYLON.Tools.CheckExtends(maxBox, min, max);
                }
            }
            return {
                min: min,
                max: max
            };
        };
        /** @hidden */
        AbstractMesh.prototype._updateBoundingInfo = function () {
            this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
            this._boundingInfo.update(this.worldMatrixFromCache);
            this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
            return this;
        };
        /** @hidden */
        AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
            if (!this.subMeshes) {
                return this;
            }
            var count = this.subMeshes.length;
            for (var subIndex = 0; subIndex < count; subIndex++) {
                var subMesh = this.subMeshes[subIndex];
                if (count > 1 || !subMesh.IsGlobal) {
                    subMesh.updateBoundingInfo(matrix);
                }
            }
            return this;
        };
        /** @hidden */
        AbstractMesh.prototype._afterComputeWorldMatrix = function () {
            // Bounding info
            this._updateBoundingInfo();
        };
        /**
         * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
         * A mesh is in the frustum if its bounding box intersects the frustum
         * @param frustumPlanes defines the frustum to test
         * @returns true if the mesh is in the frustum planes
         */
        AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
            return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
        };
        /**
         * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
         * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
         * @param frustumPlanes defines the frustum to test
         * @returns true if the mesh is completely in the frustum planes
         */
        AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
        };
        /**
         * True if the mesh intersects another mesh or a SolidParticle object
         * @param mesh defines a target mesh or SolidParticle to test
         * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
         * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
         * @returns true if there is an intersection
         */
        AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
            if (precise === void 0) { precise = false; }
            if (!this._boundingInfo || !mesh._boundingInfo) {
                return false;
            }
            if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
                return true;
            }
            if (includeDescendants) {
                for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
                    var child = _a[_i];
                    if (child.intersectsMesh(mesh, precise, true)) {
                        return true;
                    }
                }
            }
            return false;
        };
        /**
         * Returns true if the passed point (Vector3) is inside the mesh bounding box
         * @param point defines the point to test
         * @returns true if there is an intersection
         */
        AbstractMesh.prototype.intersectsPoint = function (point) {
            if (!this._boundingInfo) {
                return false;
            }
            return this._boundingInfo.intersectsPoint(point);
        };
        /**
         * Gets the position of the current mesh in camera space
         * @param camera defines the camera to use
         * @returns a position
         */
        AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
            if (camera === void 0) { camera = null; }
            if (!camera) {
                camera = this.getScene().activeCamera;
            }
            return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
        };
        /**
         * Returns the distance from the mesh to the active camera
         * @param camera defines the camera to use
         * @returns the distance
         */
        AbstractMesh.prototype.getDistanceToCamera = function (camera) {
            if (camera === void 0) { camera = null; }
            if (!camera) {
                camera = this.getScene().activeCamera;
            }
            return this.absolutePosition.subtract(camera.position).length();
        };
        Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
            // Collisions
            /**
             * Gets or sets a boolean indicating that this mesh can be used in the collision engine
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
             */
            get: function () {
                return this._checkCollisions;
            },
            set: function (collisionEnabled) {
                this._checkCollisions = collisionEnabled;
                if (this.getScene().workerCollisions) {
                    this.getScene().collisionCoordinator.onMeshUpdated(this);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractMesh.prototype, "collider", {
            /**
             * Gets Collider object used to compute collisions (not physics)
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
             */
            get: function () {
                return this._collider;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Move the mesh using collision engine
         * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
         * @param displacement defines the requested displacement vector
         * @returns the current mesh
         */
        AbstractMesh.prototype.moveWithCollisions = function (displacement) {
            var globalPosition = this.getAbsolutePosition();
            globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
            if (!this._collider) {
                this._collider = new BABYLON.Collider();
            }
            this._collider._radius = this.ellipsoid;
            this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
            return this;
        };
        // Collisions
        /** @hidden */
        AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
            this._generatePointsArray();
            if (!this._positions) {
                return this;
            }
            // Transformation
            if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
                subMesh._lastColliderTransformMatrix = transformMatrix.clone();
                subMesh._lastColliderWorldVertices = [];
                subMesh._trianglePlanes = [];
                var start = subMesh.verticesStart;
                var end = (subMesh.verticesStart + subMesh.verticesCount);
                for (var i = start; i < end; i++) {
                    subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
                }
            }
            // Collide
            collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
            if (collider.collisionFound) {
                collider.collidedMesh = this;
            }
            return this;
        };
        /** @hidden */
        AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
            var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
            var len = subMeshes.length;
            for (var index = 0; index < len; index++) {
                var subMesh = subMeshes.data[index];
                // Bounding test
                if (len > 1 && !subMesh._checkCollision(collider)) {
                    continue;
                }
                this._collideForSubMesh(subMesh, transformMatrix, collider);
            }
            return this;
        };
        /** @hidden */
        AbstractMesh.prototype._checkCollision = function (collider) {
            // Bounding box test
            if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider)) {
                return this;
            }
            // Transformation matrix
            var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
            var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
            BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
            this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
            this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
            return this;
        };
        // Picking
        /** @hidden */
        AbstractMesh.prototype._generatePointsArray = function () {
            return false;
        };
        /**
         * Checks if the passed Ray intersects with the mesh
         * @param ray defines the ray to use
         * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
         * @returns the picking info
         * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
         */
        AbstractMesh.prototype.intersects = function (ray, fastCheck) {
            var pickingInfo = new BABYLON.PickingInfo();
            if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
                return pickingInfo;
            }
            if (!this._generatePointsArray()) {
                return pickingInfo;
            }
            var intersectInfo = null;
            var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
            var len = subMeshes.length;
            for (var index = 0; index < len; index++) {
                var subMesh = subMeshes.data[index];
                // Bounding test
                if (len > 1 && !subMesh.canIntersects(ray)) {
                    continue;
                }
                var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
                if (currentIntersectInfo) {
                    if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
                        intersectInfo = currentIntersectInfo;
                        intersectInfo.subMeshId = index;
                        if (fastCheck) {
                            break;
                        }
                    }
                }
            }
            if (intersectInfo) {
                // Get picked point
                var world = this.getWorldMatrix();
                var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
                var direction = ray.direction.clone();
                direction = direction.scale(intersectInfo.distance);
                var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
                var pickedPoint = worldOrigin.add(worldDirection);
                // Return result
                pickingInfo.hit = true;
                pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
                pickingInfo.pickedPoint = pickedPoint;
                pickingInfo.pickedMesh = this;
                pickingInfo.bu = intersectInfo.bu || 0;
                pickingInfo.bv = intersectInfo.bv || 0;
                pickingInfo.faceId = intersectInfo.faceId;
                pickingInfo.subMeshId = intersectInfo.subMeshId;
                return pickingInfo;
            }
            return pickingInfo;
        };
        /**
         * Clones the current mesh
         * @param name defines the mesh name
         * @param newParent defines the new mesh parent
         * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
         * @returns the new mesh
         */
        AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
            return null;
        };
        /**
         * Disposes all the submeshes of the current meshnp
         * @returns the current mesh
         */
        AbstractMesh.prototype.releaseSubMeshes = function () {
            if (this.subMeshes) {
                while (this.subMeshes.length) {
                    this.subMeshes[0].dispose();
                }
            }
            else {
                this.subMeshes = new Array();
            }
            return this;
        };
        /**
         * Releases resources associated with this abstract mesh.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            var _this = this;
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            var index;
            // Smart Array Retainers.
            this.getScene().freeActiveMeshes();
            this.getScene().freeRenderingGroups();
            // Action manager
            if (this.actionManager !== undefined && this.actionManager !== null) {
                this.actionManager.dispose();
                this.actionManager = null;
            }
            // Skeleton
            this._skeleton = null;
            // Intersections in progress
            for (index = 0; index < this._intersectionsInProgress.length; index++) {
                var other = this._intersectionsInProgress[index];
                var pos = other._intersectionsInProgress.indexOf(this);
                other._intersectionsInProgress.splice(pos, 1);
            }
            this._intersectionsInProgress = [];
            // Lights
            var lights = this.getScene().lights;
            lights.forEach(function (light) {
                var meshIndex = light.includedOnlyMeshes.indexOf(_this);
                if (meshIndex !== -1) {
                    light.includedOnlyMeshes.splice(meshIndex, 1);
                }
                meshIndex = light.excludedMeshes.indexOf(_this);
                if (meshIndex !== -1) {
                    light.excludedMeshes.splice(meshIndex, 1);
                }
                // Shadow generators
                var generator = light.getShadowGenerator();
                if (generator) {
                    var shadowMap = generator.getShadowMap();
                    if (shadowMap && shadowMap.renderList) {
                        meshIndex = shadowMap.renderList.indexOf(_this);
                        if (meshIndex !== -1) {
                            shadowMap.renderList.splice(meshIndex, 1);
                        }
                    }
                }
            });
            // SubMeshes
            if (this.getClassName() !== "InstancedMesh") {
                this.releaseSubMeshes();
            }
            // Query
            var engine = this.getScene().getEngine();
            if (this._occlusionQuery) {
                this.isOcclusionQueryInProgress = false;
                engine.deleteQuery(this._occlusionQuery);
                this._occlusionQuery = null;
            }
            // Engine
            engine.wipeCaches();
            // Remove from scene
            this.getScene().removeMesh(this);
            if (disposeMaterialAndTextures) {
                if (this.material) {
                    this.material.dispose(false, true);
                }
            }
            if (!doNotRecurse) {
                // Particles
                for (index = 0; index < this.getScene().particleSystems.length; index++) {
                    if (this.getScene().particleSystems[index].emitter === this) {
                        this.getScene().particleSystems[index].dispose();
                        index--;
                    }
                }
            }
            // facet data
            if (this._facetData.facetDataEnabled) {
                this.disableFacetData();
            }
            this.onAfterWorldMatrixUpdateObservable.clear();
            this.onCollideObservable.clear();
            this.onCollisionPositionChangeObservable.clear();
            this.onRebuildObservable.clear();
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        /**
         * Adds the passed mesh as a child to the current mesh
         * @param mesh defines the child mesh
         * @returns the current mesh
         */
        AbstractMesh.prototype.addChild = function (mesh) {
            mesh.setParent(this);
            return this;
        };
        /**
         * Removes the passed mesh from the current mesh children list
         * @param mesh defines the child mesh
         * @returns the current mesh
         */
        AbstractMesh.prototype.removeChild = function (mesh) {
            mesh.setParent(null);
            return this;
        };
        // Facet data
        /** @hidden */
        AbstractMesh.prototype._initFacetData = function () {
            var data = this._facetData;
            if (!data.facetNormals) {
                data.facetNormals = new Array();
            }
            if (!data.facetPositions) {
                data.facetPositions = new Array();
            }
            if (!data.facetPartitioning) {
                data.facetPartitioning = new Array();
            }
            data.facetNb = (this.getIndices().length / 3) | 0;
            data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
            data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
            for (var f = 0; f < data.facetNb; f++) {
                data.facetNormals[f] = BABYLON.Vector3.Zero();
                data.facetPositions[f] = BABYLON.Vector3.Zero();
            }
            data.facetDataEnabled = true;
            return this;
        };
        /**
         * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
         * This method can be called within the render loop.
         * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation
         * @returns the current mesh
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.updateFacetData = function () {
            var data = this._facetData;
            if (!data.facetDataEnabled) {
                this._initFacetData();
            }
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this.getIndices();
            var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var bInfo = this.getBoundingInfo();
            if (data.facetDepthSort && !data.facetDepthSortEnabled) {
                // init arrays, matrix and sort function on first call
                data.facetDepthSortEnabled = true;
                if (indices instanceof Uint16Array) {
                    data.depthSortedIndices = new Uint16Array(indices);
                }
                else if (indices instanceof Uint32Array) {
                    data.depthSortedIndices = new Uint32Array(indices);
                }
                else {
                    var needs32bits = false;
                    for (var i = 0; i < indices.length; i++) {
                        if (indices[i] > 65535) {
                            needs32bits = true;
                            break;
                        }
                    }
                    if (needs32bits) {
                        data.depthSortedIndices = new Uint32Array(indices);
                    }
                    else {
                        data.depthSortedIndices = new Uint16Array(indices);
                    }
                }
                data.facetDepthSortFunction = function (f1, f2) {
                    return (f2.sqDistance - f1.sqDistance);
                };
                if (!data.facetDepthSortFrom) {
                    var camera = this.getScene().activeCamera;
                    data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
                }
                data.depthSortedFacets = [];
                for (var f = 0; f < data.facetNb; f++) {
                    var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
                    data.depthSortedFacets.push(depthSortedFacet);
                }
                data.invertedMatrix = BABYLON.Matrix.Identity();
                data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
            }
            data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
            data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
            data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
            var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
            bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
            data.subDiv.max = data.partitioningSubdivisions;
            data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
            data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
            data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
            data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
            data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
            data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
            // set the parameters for ComputeNormals()
            data.facetParameters.facetNormals = this.getFacetLocalNormals();
            data.facetParameters.facetPositions = this.getFacetLocalPositions();
            data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
            data.facetParameters.bInfo = bInfo;
            data.facetParameters.bbSize = data.bbSize;
            data.facetParameters.subDiv = data.subDiv;
            data.facetParameters.ratio = this.partitioningBBoxRatio;
            data.facetParameters.depthSort = data.facetDepthSort;
            if (data.facetDepthSort && data.facetDepthSortEnabled) {
                this.computeWorldMatrix(true);
                this._worldMatrix.invertToRef(data.invertedMatrix);
                BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
                data.facetParameters.distanceTo = data.facetDepthSortOrigin;
            }
            data.facetParameters.depthSortedFacets = data.depthSortedFacets;
            BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
            if (data.facetDepthSort && data.facetDepthSortEnabled) {
                data.depthSortedFacets.sort(data.facetDepthSortFunction);
                var l = (data.depthSortedIndices.length / 3) | 0;
                for (var f = 0; f < l; f++) {
                    var sind = data.depthSortedFacets[f].ind;
                    data.depthSortedIndices[f * 3] = indices[sind];
                    data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
                    data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
                }
                this.updateIndices(data.depthSortedIndices);
            }
            return this;
        };
        /**
         * Returns the facetLocalNormals array.
         * The normals are expressed in the mesh local spac
         * @returns an array of Vector3
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetLocalNormals = function () {
            if (!this._facetData.facetNormals) {
                this.updateFacetData();
            }
            return this._facetData.facetNormals;
        };
        /**
         * Returns the facetLocalPositions array.
         * The facet positions are expressed in the mesh local space
         * @returns an array of Vector3
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetLocalPositions = function () {
            if (!this._facetData.facetPositions) {
                this.updateFacetData();
            }
            return this._facetData.facetPositions;
        };
        /**
         * Returns the facetLocalPartioning array
         * @returns an array of array of numbers
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetLocalPartitioning = function () {
            if (!this._facetData.facetPartitioning) {
                this.updateFacetData();
            }
            return this._facetData.facetPartitioning;
        };
        /**
         * Returns the i-th facet position in the world system.
         * This method allocates a new Vector3 per call
         * @param i defines the facet index
         * @returns a new Vector3
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetPosition = function (i) {
            var pos = BABYLON.Vector3.Zero();
            this.getFacetPositionToRef(i, pos);
            return pos;
        };
        /**
         * Sets the reference Vector3 with the i-th facet position in the world system
         * @param i defines the facet index
         * @param ref defines the target vector
         * @returns the current mesh
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
            var localPos = (this.getFacetLocalPositions())[i];
            var world = this.getWorldMatrix();
            BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
            return this;
        };
        /**
         * Returns the i-th facet normal in the world system.
         * This method allocates a new Vector3 per call
         * @param i defines the facet index
         * @returns a new Vector3
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetNormal = function (i) {
            var norm = BABYLON.Vector3.Zero();
            this.getFacetNormalToRef(i, norm);
            return norm;
        };
        /**
         * Sets the reference Vector3 with the i-th facet normal in the world system
         * @param i defines the facet index
         * @param ref defines the target vector
         * @returns the current mesh
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
            var localNorm = (this.getFacetLocalNormals())[i];
            BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
            return this;
        };
        /**
         * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system)
         * @param x defines x coordinate
         * @param y defines y coordinate
         * @param z defines z coordinate
         * @returns the array of facet indexes
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
            var bInfo = this.getBoundingInfo();
            var data = this._facetData;
            var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
            var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
            var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
            if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
                return null;
            }
            return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
        };
        /**
         * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
         * @param projected sets as the (x,y,z) world projection on the facet
         * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
         * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
         * @param x defines x coordinate
         * @param y defines y coordinate
         * @param z defines z coordinate
         * @returns the face index if found (or null instead)
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
            if (checkFace === void 0) { checkFace = false; }
            if (facing === void 0) { facing = true; }
            var world = this.getWorldMatrix();
            var invMat = BABYLON.Tmp.Matrix[5];
            world.invertToRef(invMat);
            var invVect = BABYLON.Tmp.Vector3[8];
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
            var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
            if (projected) {
                // tranform the local computed projected vector to world coordinates
                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
            }
            return closest;
        };
        /**
         * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
         * @param projected sets as the (x,y,z) local projection on the facet
         * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
         * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
         * @param x defines x coordinate
         * @param y defines y coordinate
         * @param z defines z coordinate
         * @returns the face index if found (or null instead)
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
            if (checkFace === void 0) { checkFace = false; }
            if (facing === void 0) { facing = true; }
            var closest = null;
            var tmpx = 0.0;
            var tmpy = 0.0;
            var tmpz = 0.0;
            var d = 0.0; // tmp dot facet normal * facet position
            var t0 = 0.0;
            var projx = 0.0;
            var projy = 0.0;
            var projz = 0.0;
            // Get all the facets in the same partitioning block than (x, y, z)
            var facetPositions = this.getFacetLocalPositions();
            var facetNormals = this.getFacetLocalNormals();
            var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
            if (!facetsInBlock) {
                return null;
            }
            // Get the closest facet to (x, y, z)
            var shortest = Number.MAX_VALUE; // init distance vars
            var tmpDistance = shortest;
            var fib; // current facet in the block
            var norm; // current facet normal
            var p0; // current facet barycenter position
            // loop on all the facets in the current partitioning block
            for (var idx = 0; idx < facetsInBlock.length; idx++) {
                fib = facetsInBlock[idx];
                norm = facetNormals[fib];
                p0 = facetPositions[fib];
                d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
                if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
                    // compute (x,y,z) projection on the facet = (projx, projy, projz)
                    d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
                    t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
                    projx = x + norm.x * t0;
                    projy = y + norm.y * t0;
                    projz = z + norm.z * t0;
                    tmpx = projx - x;
                    tmpy = projy - y;
                    tmpz = projz - z;
                    tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
                    if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
                        shortest = tmpDistance;
                        closest = fib;
                        if (projected) {
                            projected.x = projx;
                            projected.y = projy;
                            projected.z = projz;
                        }
                    }
                }
            }
            return closest;
        };
        /**
         * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
         * @returns the parameters
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.getFacetDataParameters = function () {
            return this._facetData.facetParameters;
        };
        /**
         * Disables the feature FacetData and frees the related memory
         * @returns the current mesh
         * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
         */
        AbstractMesh.prototype.disableFacetData = function () {
            if (this._facetData.facetDataEnabled) {
                this._facetData.facetDataEnabled = false;
                this._facetData.facetPositions = new Array();
                this._facetData.facetNormals = new Array();
                this._facetData.facetPartitioning = new Array();
                this._facetData.facetParameters = null;
                this._facetData.depthSortedIndices = new Uint32Array(0);
            }
            return this;
        };
        /**
         * Updates the AbstractMesh indices array
         * @param indices defines the data source
         * @returns the current mesh
         */
        AbstractMesh.prototype.updateIndices = function (indices) {
            return this;
        };
        /**
         * Creates new normals data for the mesh
         * @param updatable defines if the normal vertex buffer must be flagged as updatable
         * @returns the current mesh
         */
        AbstractMesh.prototype.createNormals = function (updatable) {
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this.getIndices();
            var normals;
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            }
            else {
                normals = [];
            }
            BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
            this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
            return this;
        };
        /**
         * Align the mesh with a normal
         * @param normal defines the normal to use
         * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
         * @returns the current mesh
         */
        AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
            if (!upDirection) {
                upDirection = BABYLON.Axis.Y;
            }
            var axisX = BABYLON.Tmp.Vector3[0];
            var axisZ = BABYLON.Tmp.Vector3[1];
            BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
            BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
            if (this.rotationQuaternion) {
                BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
            }
            else {
                BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
            }
            return this;
        };
        /** @hidden */
        AbstractMesh.prototype._checkOcclusionQuery = function () {
            return false;
        };
        /** No occlusion */
        AbstractMesh.OCCLUSION_TYPE_NONE = 0;
        /** Occlusion set to optimisitic */
        AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
        /** Occlusion set to strict */
        AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
        /** Use an accurante occlusion algorithm */
        AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
        /** Use a conservative occlusion algorithm */
        AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
        /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
        AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
        /** Culling strategy with bounding sphere only and then frustum culling */
        AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
        return AbstractMesh;
    }(BABYLON.TransformNode));
    BABYLON.AbstractMesh = AbstractMesh;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.abstractMesh.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Base class of all the lights in Babylon. It groups all the generic information about lights.
     * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
     * All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
     */
    var Light = /** @class */ (function (_super) {
        __extends(Light, _super);
        /**
         * Creates a Light object in the scene.
         * Documentation : http://doc.babylonjs.com/tutorials/lights
         * @param name The firendly name of the light
         * @param scene The scene the light belongs too
         */
        function Light(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * Diffuse gives the basic color to an object.
             */
            _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
            /**
             * Specular produces a highlight color on an object.
             * Note: This is note affecting PBR materials.
             */
            _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
            /**
             * Defines the falloff type for this light. This lets overrriding how punctual light are
             * falling off base on range or angle.
             * This can be set to any values in Light.FALLOFF_x.
             *
             * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
             * other types of materials.
             */
            _this.falloffType = Light.FALLOFF_DEFAULT;
            /**
             * Strength of the light.
             * Note: By default it is define in the framework own unit.
             * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
             */
            _this.intensity = 1.0;
            _this._range = Number.MAX_VALUE;
            _this._inverseSquaredRange = 0;
            /**
             * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
             * of light.
             */
            _this._photometricScale = 1.0;
            _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
            _this._radius = 0.00001;
            /**
             * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
             * exceeding the number allowed of the materials.
             */
            _this.renderPriority = 0;
            _this._shadowEnabled = true;
            _this._excludeWithLayerMask = 0;
            _this._includeOnlyWithLayerMask = 0;
            _this._lightmapMode = 0;
            /**
             * @hidden Internal use only.
             */
            _this._excludedMeshesIds = new Array();
            /**
             * @hidden Internal use only.
             */
            _this._includedOnlyMeshesIds = new Array();
            _this.getScene().addLight(_this);
            _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
            _this._buildUniformLayout();
            _this.includedOnlyMeshes = new Array();
            _this.excludedMeshes = new Array();
            _this._resyncMeshes();
            return _this;
        }
        Object.defineProperty(Light.prototype, "range", {
            /**
             * Defines how far from the source the light is impacting in scene units.
             * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
             */
            get: function () {
                return this._range;
            },
            /**
             * Defines how far from the source the light is impacting in scene units.
             * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
             */
            set: function (value) {
                this._range = value;
                this._inverseSquaredRange = 1.0 / (this.range * this.range);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "intensityMode", {
            /**
             * Gets the photometric scale used to interpret the intensity.
             * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
             */
            get: function () {
                return this._intensityMode;
            },
            /**
             * Sets the photometric scale used to interpret the intensity.
             * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
             */
            set: function (value) {
                this._intensityMode = value;
                this._computePhotometricScale();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "radius", {
            /**
             * Gets the light radius used by PBR Materials to simulate soft area lights.
             */
            get: function () {
                return this._radius;
            },
            /**
             * sets the light radius used by PBR Materials to simulate soft area lights.
             */
            set: function (value) {
                this._radius = value;
                this._computePhotometricScale();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "shadowEnabled", {
            /**
             * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
             * the current shadow generator.
             */
            get: function () {
                return this._shadowEnabled;
            },
            /**
             * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
             * the current shadow generator.
             */
            set: function (value) {
                if (this._shadowEnabled === value) {
                    return;
                }
                this._shadowEnabled = value;
                this._markMeshesAsLightDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
            /**
             * Gets the only meshes impacted by this light.
             */
            get: function () {
                return this._includedOnlyMeshes;
            },
            /**
             * Sets the only meshes impacted by this light.
             */
            set: function (value) {
                this._includedOnlyMeshes = value;
                this._hookArrayForIncludedOnly(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "excludedMeshes", {
            /**
             * Gets the meshes not impacted by this light.
             */
            get: function () {
                return this._excludedMeshes;
            },
            /**
             * Sets the meshes not impacted by this light.
             */
            set: function (value) {
                this._excludedMeshes = value;
                this._hookArrayForExcluded(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
            /**
             * Gets the layer id use to find what meshes are not impacted by the light.
             * Inactive if 0
             */
            get: function () {
                return this._excludeWithLayerMask;
            },
            /**
             * Sets the layer id use to find what meshes are not impacted by the light.
             * Inactive if 0
             */
            set: function (value) {
                this._excludeWithLayerMask = value;
                this._resyncMeshes();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
            /**
             * Gets the layer id use to find what meshes are impacted by the light.
             * Inactive if 0
             */
            get: function () {
                return this._includeOnlyWithLayerMask;
            },
            /**
             * Sets the layer id use to find what meshes are impacted by the light.
             * Inactive if 0
             */
            set: function (value) {
                this._includeOnlyWithLayerMask = value;
                this._resyncMeshes();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Light.prototype, "lightmapMode", {
            /**
             * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
             */
            get: function () {
                return this._lightmapMode;
            },
            /**
             * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
             */
            set: function (value) {
                if (this._lightmapMode === value) {
                    return;
                }
                this._lightmapMode = value;
                this._markMeshesAsLightDirty();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "Light".
         * @returns the class name
         */
        Light.prototype.getClassName = function () {
            return "Light";
        };
        /**
         * Converts the light information to a readable string for debug purpose.
         * @param fullDetails Supports for multiple levels of logging within scene loading
         * @returns the human readable light info
         */
        Light.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
            if (this.animations) {
                for (var i = 0; i < this.animations.length; i++) {
                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
                }
            }
            if (fullDetails) {
            }
            return ret;
        };
        /** @hidden */
        Light.prototype._syncParentEnabledState = function () {
            _super.prototype._syncParentEnabledState.call(this);
            this._resyncMeshes();
        };
        /**
         * Set the enabled state of this node.
         * @param value - the new enabled state
         */
        Light.prototype.setEnabled = function (value) {
            _super.prototype.setEnabled.call(this, value);
            this._resyncMeshes();
        };
        /**
         * Returns the Light associated shadow generator if any.
         * @return the associated shadow generator.
         */
        Light.prototype.getShadowGenerator = function () {
            return this._shadowGenerator;
        };
        /**
         * Returns a Vector3, the absolute light position in the World.
         * @returns the world space position of the light
         */
        Light.prototype.getAbsolutePosition = function () {
            return BABYLON.Vector3.Zero();
        };
        /**
         * Specifies if the light will affect the passed mesh.
         * @param mesh The mesh to test against the light
         * @return true the mesh is affected otherwise, false.
         */
        Light.prototype.canAffectMesh = function (mesh) {
            if (!mesh) {
                return true;
            }
            if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
                return false;
            }
            if (this.excludedMeshes && 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;
        };
        /**
         * Sort function to order lights for rendering.
         * @param a First Light object to compare to second.
         * @param b Second Light object to compare first.
         * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
         */
        Light.CompareLightsPriority = function (a, b) {
            //shadow-casting lights have priority over non-shadow-casting lights
            //the renderPrioirty is a secondary sort criterion
            if (a.shadowEnabled !== b.shadowEnabled) {
                return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
            }
            return b.renderPriority - a.renderPriority;
        };
        /**
         * Releases resources associated with this node.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            if (this._shadowGenerator) {
                this._shadowGenerator.dispose();
                this._shadowGenerator = null;
            }
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from meshes
            for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                mesh._removeLightSource(this);
            }
            this._uniformBuffer.dispose();
            // Remove from scene
            this.getScene().removeLight(this);
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        /**
         * Returns the light type ID (integer).
         * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
         */
        Light.prototype.getTypeID = function () {
            return 0;
        };
        /**
         * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
         * @returns the scaled intensity in intensity mode unit
         */
        Light.prototype.getScaledIntensity = function () {
            return this._photometricScale * this.intensity;
        };
        /**
         * Returns a new Light object, named "name", from the current one.
         * @param name The name of the cloned light
         * @returns the new created light
         */
        Light.prototype.clone = function (name) {
            var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
            if (!constructor) {
                return null;
            }
            return BABYLON.SerializationHelper.Clone(constructor, this);
        };
        /**
         * Serializes the current light into a Serialization object.
         * @returns the serialized object.
         */
        Light.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            // Type
            serializationObject.type = this.getTypeID();
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            // Inclusion / exclusions
            if (this.excludedMeshes.length > 0) {
                serializationObject.excludedMeshesIds = [];
                this.excludedMeshes.forEach(function (mesh) {
                    serializationObject.excludedMeshesIds.push(mesh.id);
                });
            }
            if (this.includedOnlyMeshes.length > 0) {
                serializationObject.includedOnlyMeshesIds = [];
                this.includedOnlyMeshes.forEach(function (mesh) {
                    serializationObject.includedOnlyMeshesIds.push(mesh.id);
                });
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            serializationObject.ranges = this.serializeAnimationRanges();
            return serializationObject;
        };
        /**
         * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
         * This new light is named "name" and added to the passed scene.
         * @param type Type according to the types available in Light.LIGHTTYPEID_x
         * @param name The friendly name of the light
         * @param scene The scene the new light will belong to
         * @returns the constructor function
         */
        Light.GetConstructorFromName = function (type, name, scene) {
            var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
            if (constructorFunc) {
                return constructorFunc;
            }
            // Default to no light for none present once.
            return null;
        };
        /**
         * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
         * @param parsedLight The JSON representation of the light
         * @param scene The scene to create the parsed light in
         * @returns the created light after parsing
         */
        Light.Parse = function (parsedLight, scene) {
            var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
            if (!constructor) {
                return null;
            }
            var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
            // Inclusion / exclusions
            if (parsedLight.excludedMeshesIds) {
                light._excludedMeshesIds = parsedLight.excludedMeshesIds;
            }
            if (parsedLight.includedOnlyMeshesIds) {
                light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
            }
            // Parent
            if (parsedLight.parentId) {
                light._waitingParentId = parsedLight.parentId;
            }
            // Animations
            if (parsedLight.animations) {
                for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
                    var parsedAnimation = parsedLight.animations[animationIndex];
                    light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
            }
            if (parsedLight.autoAnimate) {
                scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
            }
            return light;
        };
        Light.prototype._hookArrayForExcluded = function (array) {
            var _this = this;
            var oldPush = array.push;
            array.push = function () {
                var items = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    items[_i] = arguments[_i];
                }
                var result = oldPush.apply(array, items);
                for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
                    var item = items_1[_a];
                    item._resyncLighSource(_this);
                }
                return result;
            };
            var oldSplice = array.splice;
            array.splice = function (index, deleteCount) {
                var deleted = oldSplice.apply(array, [index, deleteCount]);
                for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
                    var item = deleted_1[_i];
                    item._resyncLighSource(_this);
                }
                return deleted;
            };
            for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
                var item = array_1[_i];
                item._resyncLighSource(this);
            }
        };
        Light.prototype._hookArrayForIncludedOnly = function (array) {
            var _this = this;
            var oldPush = array.push;
            array.push = function () {
                var items = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    items[_i] = arguments[_i];
                }
                var result = oldPush.apply(array, items);
                _this._resyncMeshes();
                return result;
            };
            var oldSplice = array.splice;
            array.splice = function (index, deleteCount) {
                var deleted = oldSplice.apply(array, [index, deleteCount]);
                _this._resyncMeshes();
                return deleted;
            };
            this._resyncMeshes();
        };
        Light.prototype._resyncMeshes = function () {
            for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                mesh._resyncLighSource(this);
            }
        };
        /**
         * Forces the meshes to update their light related information in their rendering used effects
         * @hidden Internal Use Only
         */
        Light.prototype._markMeshesAsLightDirty = function () {
            for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                if (mesh._lightSources.indexOf(this) !== -1) {
                    mesh._markSubMeshesAsLightDirty();
                }
            }
        };
        /**
         * Recomputes the cached photometric scale if needed.
         */
        Light.prototype._computePhotometricScale = function () {
            this._photometricScale = this._getPhotometricScale();
            this.getScene().resetCachedMaterial();
        };
        /**
         * Returns the Photometric Scale according to the light type and intensity mode.
         */
        Light.prototype._getPhotometricScale = function () {
            var photometricScale = 0.0;
            var lightTypeID = this.getTypeID();
            //get photometric mode
            var photometricMode = this.intensityMode;
            if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
                if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
                    photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
                }
                else {
                    photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
                }
            }
            //compute photometric scale
            switch (lightTypeID) {
                case Light.LIGHTTYPEID_POINTLIGHT:
                case Light.LIGHTTYPEID_SPOTLIGHT:
                    switch (photometricMode) {
                        case Light.INTENSITYMODE_LUMINOUSPOWER:
                            photometricScale = 1.0 / (4.0 * Math.PI);
                            break;
                        case Light.INTENSITYMODE_LUMINOUSINTENSITY:
                            photometricScale = 1.0;
                            break;
                        case Light.INTENSITYMODE_LUMINANCE:
                            photometricScale = this.radius * this.radius;
                            break;
                    }
                    break;
                case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
                    switch (photometricMode) {
                        case Light.INTENSITYMODE_ILLUMINANCE:
                            photometricScale = 1.0;
                            break;
                        case Light.INTENSITYMODE_LUMINANCE:
                            // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
                            // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
                            var apexAngleRadians = this.radius;
                            // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
                            apexAngleRadians = Math.max(apexAngleRadians, 0.001);
                            var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
                            photometricScale = solidAngle;
                            break;
                    }
                    break;
                case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
                    // No fall off in hemisperic light.
                    photometricScale = 1.0;
                    break;
            }
            return photometricScale;
        };
        /**
         * Reorder the light in the scene according to their defined priority.
         * @hidden Internal Use Only
         */
        Light.prototype._reorderLightsInScene = function () {
            var scene = this.getScene();
            if (this._renderPriority != 0) {
                scene.requireLightSorting = true;
            }
            this.getScene().sortLightsByPriority();
        };
        /**
         * Falloff Default: light is falling off following the material specification:
         * standard material is using standard falloff whereas pbr material can request special falloff per materials.
         */
        Light.FALLOFF_DEFAULT = 0;
        /**
         * Falloff Physical: light is falling off following the inverse squared distance law.
         */
        Light.FALLOFF_PHYSICAL = 1;
        /**
         * Falloff gltf: light is falling off as described in the gltf moving to PBR document
         * to enhance interoperability with other engines.
         */
        Light.FALLOFF_GLTF = 2;
        /**
         * Falloff Standard: light is falling off like in the standard material
         * to enhance interoperability with other materials.
         */
        Light.FALLOFF_STANDARD = 3;
        //lightmapMode Consts
        /**
         * If every light affecting the material is in this lightmapMode,
         * material.lightmapTexture adds or multiplies
         * (depends on material.useLightmapAsShadowmap)
         * after every other light calculations.
         */
        Light.LIGHTMAP_DEFAULT = 0;
        /**
         * material.lightmapTexture as only diffuse lighting from this light
         * adds only specular lighting from this light
         * adds dynamic shadows
         */
        Light.LIGHTMAP_SPECULAR = 1;
        /**
         * material.lightmapTexture as only lighting
         * no light calculation from this light
         * only adds dynamic shadows from this light
         */
        Light.LIGHTMAP_SHADOWSONLY = 2;
        // Intensity Mode Consts
        /**
         * Each light type uses the default quantity according to its type:
         *      point/spot lights use luminous intensity
         *      directional lights use illuminance
         */
        Light.INTENSITYMODE_AUTOMATIC = 0;
        /**
         * lumen (lm)
         */
        Light.INTENSITYMODE_LUMINOUSPOWER = 1;
        /**
         * candela (lm/sr)
         */
        Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
        /**
         * lux (lm/m^2)
         */
        Light.INTENSITYMODE_ILLUMINANCE = 3;
        /**
         * nit (cd/m^2)
         */
        Light.INTENSITYMODE_LUMINANCE = 4;
        // Light types ids const.
        /**
         * Light type const id of the point light.
         */
        Light.LIGHTTYPEID_POINTLIGHT = 0;
        /**
         * Light type const id of the directional light.
         */
        Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
        /**
         * Light type const id of the spot light.
         */
        Light.LIGHTTYPEID_SPOTLIGHT = 2;
        /**
         * Light type const id of the hemispheric light.
         */
        Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
        __decorate([
            BABYLON.serializeAsColor3()
        ], Light.prototype, "diffuse", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], Light.prototype, "specular", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "falloffType", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "intensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "range", null);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "intensityMode", null);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "radius", null);
        __decorate([
            BABYLON.serialize()
        ], Light.prototype, "_renderPriority", void 0);
        __decorate([
            BABYLON.expandToProperty("_reorderLightsInScene")
        ], Light.prototype, "renderPriority", void 0);
        __decorate([
            BABYLON.serialize("shadowEnabled")
        ], Light.prototype, "_shadowEnabled", void 0);
        __decorate([
            BABYLON.serialize("excludeWithLayerMask")
        ], Light.prototype, "_excludeWithLayerMask", void 0);
        __decorate([
            BABYLON.serialize("includeOnlyWithLayerMask")
        ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
        __decorate([
            BABYLON.serialize("lightmapMode")
        ], Light.prototype, "_lightmapMode", void 0);
        return Light;
    }(BABYLON.Node));
    BABYLON.Light = Light;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.light.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * This is the base class of all the camera used in the application.
     * @see http://doc.babylonjs.com/features/cameras
     */
    var Camera = /** @class */ (function (_super) {
        __extends(Camera, _super);
        /**
         * Instantiates a new camera object.
         * This should not be used directly but through the inherited cameras: ArcRotate, Free...
         * @see http://doc.babylonjs.com/features/cameras
         * @param name Defines the name of the camera in the scene
         * @param position Defines the position of the camera
         * @param scene Defines the scene the camera belongs too
         * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
         */
        function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
            if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
            var _this = _super.call(this, name, scene) || this;
            /**
             * The vector the camera should consider as up.
             * (default is Vector3(0, 1, 0) aka Vector3.Up())
             */
            _this.upVector = BABYLON.Vector3.Up();
            /**
             * Define the current limit on the left side for an orthographic camera
             * In scene unit
             */
            _this.orthoLeft = null;
            /**
             * Define the current limit on the right side for an orthographic camera
             * In scene unit
             */
            _this.orthoRight = null;
            /**
             * Define the current limit on the bottom side for an orthographic camera
             * In scene unit
             */
            _this.orthoBottom = null;
            /**
             * Define the current limit on the top side for an orthographic camera
             * In scene unit
             */
            _this.orthoTop = null;
            /**
             * Field Of View is set in Radians. (default is 0.8)
             */
            _this.fov = 0.8;
            /**
             * Define the minimum distance the camera can see from.
             * This is important to note that the depth buffer are not infinite and the closer it starts
             * the more your scene might encounter depth fighting issue.
             */
            _this.minZ = 1;
            /**
             * Define the maximum distance the camera can see to.
             * This is important to note that the depth buffer are not infinite and the further it end
             * the more your scene might encounter depth fighting issue.
             */
            _this.maxZ = 10000.0;
            /**
             * Define the default inertia of the camera.
             * This helps giving a smooth feeling to the camera movement.
             */
            _this.inertia = 0.9;
            /**
             * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
             */
            _this.mode = Camera.PERSPECTIVE_CAMERA;
            /**
             * Define wether the camera is intermediate.
             * This is usefull to not present the output directly to the screen in case of rig without post process for instance
             */
            _this.isIntermediate = false;
            /**
             * Define the viewport of the camera.
             * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
             */
            _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
            /**
             * Restricts the camera to viewing objects with the same layerMask.
             * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
             */
            _this.layerMask = 0x0FFFFFFF;
            /**
             * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
             */
            _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
            /**
             * Rig mode of the camera.
             * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
             * This is normally controlled byt the camera themselves as internal use.
             */
            _this.cameraRigMode = Camera.RIG_MODE_NONE;
            /**
             * Defines the list of custom render target the camera should render to.
             * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
             * else in the scene.
             */
            _this.customRenderTargets = new Array();
            /**
             * Observable triggered when the camera view matrix has changed.
             */
            _this.onViewMatrixChangedObservable = new BABYLON.Observable();
            /**
             * Observable triggered when the camera Projection matrix has changed.
             */
            _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
            /**
             * Observable triggered when the inputs have been processed.
             */
            _this.onAfterCheckInputsObservable = new BABYLON.Observable();
            /**
             * Observable triggered when reset has been called and applied to the camera.
             */
            _this.onRestoreStateObservable = new BABYLON.Observable();
            /** @hidden */
            _this._rigCameras = new Array();
            _this._webvrViewMatrix = BABYLON.Matrix.Identity();
            /** @hidden */
            _this._skipRendering = false;
            /** @hidden */
            _this._projectionMatrix = new BABYLON.Matrix();
            /** @hidden */
            _this._postProcesses = new Array();
            /** @hidden */
            _this._activeMeshes = new BABYLON.SmartArray(256);
            _this._globalPosition = BABYLON.Vector3.Zero();
            _this._computedViewMatrix = BABYLON.Matrix.Identity();
            _this._doNotComputeProjectionMatrix = false;
            _this._transformMatrix = BABYLON.Matrix.Zero();
            _this._refreshFrustumPlanes = true;
            _this.getScene().addCamera(_this);
            if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
                _this.getScene().activeCamera = _this;
            }
            _this.position = position;
            return _this;
        }
        /**
         * Store current camera state (fov, position, etc..)
         * @returns the camera
         */
        Camera.prototype.storeState = function () {
            this._stateStored = true;
            this._storedFov = this.fov;
            return this;
        };
        /**
         * Restores the camera state values if it has been stored. You must call storeState() first
         */
        Camera.prototype._restoreStateValues = function () {
            if (!this._stateStored) {
                return false;
            }
            this.fov = this._storedFov;
            return true;
        };
        /**
         * Restored camera state. You must call storeState() first.
         * @returns true if restored and false otherwise
         */
        Camera.prototype.restoreState = function () {
            if (this._restoreStateValues()) {
                this.onRestoreStateObservable.notifyObservers(this);
                return true;
            }
            return false;
        };
        /**
         * Gets the class name of the camera.
         * @returns the class name
         */
        Camera.prototype.getClassName = function () {
            return "Camera";
        };
        /**
         * Gets a string representation of the camera usefull for debug purpose.
         * @param fullDetails Defines that a more verboe level of logging is required
         * @returns the string representation
         */
        Camera.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            ret += ", type: " + this.getClassName();
            if (this.animations) {
                for (var i = 0; i < this.animations.length; i++) {
                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
                }
            }
            if (fullDetails) {
            }
            return ret;
        };
        Object.defineProperty(Camera.prototype, "globalPosition", {
            /**
             * Gets the current world space position of the camera.
             */
            get: function () {
                return this._globalPosition;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
         * @returns the active meshe list
         */
        Camera.prototype.getActiveMeshes = function () {
            return this._activeMeshes;
        };
        /**
         * Check wether a mesh is part of the current active mesh list of the camera
         * @param mesh Defines the mesh to check
         * @returns true if active, false otherwise
         */
        Camera.prototype.isActiveMesh = function (mesh) {
            return (this._activeMeshes.indexOf(mesh) !== -1);
        };
        /**
         * Is this camera ready to be used/rendered
         * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
         * @return true if the camera is ready
         */
        Camera.prototype.isReady = function (completeCheck) {
            if (completeCheck === void 0) { completeCheck = false; }
            if (completeCheck) {
                for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
                    var pp = _a[_i];
                    if (pp && !pp.isReady()) {
                        return false;
                    }
                }
            }
            return _super.prototype.isReady.call(this, completeCheck);
        };
        /** @hidden */
        Camera.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.mode = undefined;
            this._cache.minZ = undefined;
            this._cache.maxZ = undefined;
            this._cache.fov = undefined;
            this._cache.fovMode = undefined;
            this._cache.aspectRatio = undefined;
            this._cache.orthoLeft = undefined;
            this._cache.orthoRight = undefined;
            this._cache.orthoBottom = undefined;
            this._cache.orthoTop = undefined;
            this._cache.renderWidth = undefined;
            this._cache.renderHeight = undefined;
        };
        /** @hidden */
        Camera.prototype._updateCache = function (ignoreParentClass) {
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            this._cache.position.copyFrom(this.position);
            this._cache.upVector.copyFrom(this.upVector);
        };
        /** @hidden */
        Camera.prototype._isSynchronized = function () {
            return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
        };
        /** @hidden */
        Camera.prototype._isSynchronizedViewMatrix = function () {
            if (!_super.prototype._isSynchronized.call(this)) {
                return false;
            }
            return this._cache.position.equals(this.position)
                && this._cache.upVector.equals(this.upVector)
                && this.isSynchronizedWithParent();
        };
        /** @hidden */
        Camera.prototype._isSynchronizedProjectionMatrix = function () {
            var check = this._cache.mode === this.mode
                && this._cache.minZ === this.minZ
                && this._cache.maxZ === this.maxZ;
            if (!check) {
                return false;
            }
            var engine = this.getEngine();
            if (this.mode === Camera.PERSPECTIVE_CAMERA) {
                check = this._cache.fov === this.fov
                    && this._cache.fovMode === this.fovMode
                    && this._cache.aspectRatio === engine.getAspectRatio(this);
            }
            else {
                check = this._cache.orthoLeft === this.orthoLeft
                    && this._cache.orthoRight === this.orthoRight
                    && this._cache.orthoBottom === this.orthoBottom
                    && this._cache.orthoTop === this.orthoTop
                    && this._cache.renderWidth === engine.getRenderWidth()
                    && this._cache.renderHeight === engine.getRenderHeight();
            }
            return check;
        };
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        Camera.prototype.attachControl = function (element, noPreventDefault) {
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        Camera.prototype.detachControl = function (element) {
        };
        /**
         * Update the camera state according to the different inputs gathered during the frame.
         */
        Camera.prototype.update = function () {
            this._checkInputs();
            if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
                this._updateRigCameras();
            }
        };
        /** @hidden */
        Camera.prototype._checkInputs = function () {
            this.onAfterCheckInputsObservable.notifyObservers(this);
        };
        Object.defineProperty(Camera.prototype, "rigCameras", {
            /** @hidden */
            get: function () {
                return this._rigCameras;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera.prototype, "rigPostProcess", {
            /**
             * Gets the post process used by the rig cameras
             */
            get: function () {
                return this._rigPostProcess;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Internal, gets the first post proces.
         * @returns the first post process to be run on this camera.
         */
        Camera.prototype._getFirstPostProcess = function () {
            for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
                if (this._postProcesses[ppIndex] !== null) {
                    return this._postProcesses[ppIndex];
                }
            }
            return null;
        };
        Camera.prototype._cascadePostProcessesToRigCams = function () {
            // invalidate framebuffer
            var firstPostProcess = this._getFirstPostProcess();
            if (firstPostProcess) {
                firstPostProcess.markTextureDirty();
            }
            // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
            for (var i = 0, len = this._rigCameras.length; i < len; i++) {
                var cam = this._rigCameras[i];
                var rigPostProcess = cam._rigPostProcess;
                // for VR rig, there does not have to be a post process
                if (rigPostProcess) {
                    var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
                    if (isPass) {
                        // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
                        cam.isIntermediate = this._postProcesses.length === 0;
                    }
                    cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
                    rigPostProcess.markTextureDirty();
                }
                else {
                    cam._postProcesses = this._postProcesses.slice(0);
                }
            }
        };
        /**
         * Attach a post process to the camera.
         * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
         * @param postProcess The post process to attach to the camera
         * @param insertAt The position of the post process in case several of them are in use in the scene
         * @returns the position the post process has been inserted at
         */
        Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
            if (insertAt === void 0) { insertAt = null; }
            if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
                BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
                return 0;
            }
            if (insertAt == null || insertAt < 0) {
                this._postProcesses.push(postProcess);
            }
            else if (this._postProcesses[insertAt] === null) {
                this._postProcesses[insertAt] = postProcess;
            }
            else {
                this._postProcesses.splice(insertAt, 0, postProcess);
            }
            this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
            return this._postProcesses.indexOf(postProcess);
        };
        /**
         * Detach a post process to the camera.
         * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
         * @param postProcess The post process to detach from the camera
         */
        Camera.prototype.detachPostProcess = function (postProcess) {
            var idx = this._postProcesses.indexOf(postProcess);
            if (idx !== -1) {
                this._postProcesses[idx] = null;
            }
            this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
        };
        /**
         * Gets the current world matrix of the camera
         */
        Camera.prototype.getWorldMatrix = function () {
            if (this._isSynchronizedViewMatrix()) {
                return this._worldMatrix;
            }
            // Getting the the view matrix will also compute the world matrix.
            this.getViewMatrix();
            return this._worldMatrix;
        };
        /** @hidden */
        Camera.prototype._getViewMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        /**
         * Gets the current view matrix of the camera.
         * @param force forces the camera to recompute the matrix without looking at the cached state
         * @returns the view matrix
         */
        Camera.prototype.getViewMatrix = function (force) {
            if (!force && this._isSynchronizedViewMatrix()) {
                return this._computedViewMatrix;
            }
            this.updateCache();
            this._computedViewMatrix = this._getViewMatrix();
            this._currentRenderId = this.getScene().getRenderId();
            this._childRenderId = this._currentRenderId;
            this._refreshFrustumPlanes = true;
            if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
                this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
            }
            this.onViewMatrixChangedObservable.notifyObservers(this);
            this._computedViewMatrix.invertToRef(this._worldMatrix);
            return this._computedViewMatrix;
        };
        /**
         * Freeze the projection matrix.
         * It will prevent the cache check of the camera projection compute and can speed up perf
         * if no parameter of the camera are meant to change
         * @param projection Defines manually a projection if necessary
         */
        Camera.prototype.freezeProjectionMatrix = function (projection) {
            this._doNotComputeProjectionMatrix = true;
            if (projection !== undefined) {
                this._projectionMatrix = projection;
            }
        };
        /**
         * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
         */
        Camera.prototype.unfreezeProjectionMatrix = function () {
            this._doNotComputeProjectionMatrix = false;
        };
        /**
         * Gets the current projection matrix of the camera.
         * @param force forces the camera to recompute the matrix without looking at the cached state
         * @returns the projection matrix
         */
        Camera.prototype.getProjectionMatrix = function (force) {
            if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
                return this._projectionMatrix;
            }
            // Cache
            this._cache.mode = this.mode;
            this._cache.minZ = this.minZ;
            this._cache.maxZ = this.maxZ;
            // Matrix
            this._refreshFrustumPlanes = true;
            var engine = this.getEngine();
            var scene = this.getScene();
            if (this.mode === Camera.PERSPECTIVE_CAMERA) {
                this._cache.fov = this.fov;
                this._cache.fovMode = this.fovMode;
                this._cache.aspectRatio = engine.getAspectRatio(this);
                if (this.minZ <= 0) {
                    this.minZ = 0.1;
                }
                if (scene.useRightHandedSystem) {
                    BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
                }
                else {
                    BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
                }
            }
            else {
                var halfWidth = engine.getRenderWidth() / 2.0;
                var halfHeight = engine.getRenderHeight() / 2.0;
                if (scene.useRightHandedSystem) {
                    BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
                }
                else {
                    BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
                }
                this._cache.orthoLeft = this.orthoLeft;
                this._cache.orthoRight = this.orthoRight;
                this._cache.orthoBottom = this.orthoBottom;
                this._cache.orthoTop = this.orthoTop;
                this._cache.renderWidth = engine.getRenderWidth();
                this._cache.renderHeight = engine.getRenderHeight();
            }
            this.onProjectionMatrixChangedObservable.notifyObservers(this);
            return this._projectionMatrix;
        };
        /**
         * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
         * @returns a Matrix
         */
        Camera.prototype.getTransformationMatrix = function () {
            this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
            return this._transformMatrix;
        };
        Camera.prototype._updateFrustumPlanes = function () {
            if (!this._refreshFrustumPlanes) {
                return;
            }
            this.getTransformationMatrix();
            if (!this._frustumPlanes) {
                this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
            }
            else {
                BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
            }
            this._refreshFrustumPlanes = false;
        };
        /**
         * Checks if a cullable object (mesh...) is in the camera frustum
         * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
         * @param target The object to check
         * @returns true if the object is in frustum otherwise false
         */
        Camera.prototype.isInFrustum = function (target) {
            this._updateFrustumPlanes();
            return target.isInFrustum(this._frustumPlanes);
        };
        /**
         * Checks if a cullable object (mesh...) is in the camera frustum
         * Unlike isInFrustum this cheks the full bounding box
         * @param target The object to check
         * @returns true if the object is in frustum otherwise false
         */
        Camera.prototype.isCompletelyInFrustum = function (target) {
            this._updateFrustumPlanes();
            return target.isCompletelyInFrustum(this._frustumPlanes);
        };
        /**
         * Gets a ray in the forward direction from the camera.
         * @param length Defines the length of the ray to create
         * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
         * @param origin Defines the start point of the ray which defaults to the camera position
         * @returns the forward ray
         */
        Camera.prototype.getForwardRay = function (length, transform, origin) {
            if (length === void 0) { length = 100; }
            if (!transform) {
                transform = this.getWorldMatrix();
            }
            if (!origin) {
                origin = this.position;
            }
            var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
            var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
            var direction = BABYLON.Vector3.Normalize(forwardWorld);
            return new BABYLON.Ray(origin, direction, length);
        };
        /**
         * Releases resources associated with this node.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            // Observables
            this.onViewMatrixChangedObservable.clear();
            this.onProjectionMatrixChangedObservable.clear();
            this.onAfterCheckInputsObservable.clear();
            this.onRestoreStateObservable.clear();
            // Inputs
            if (this.inputs) {
                this.inputs.clear();
            }
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            this.getScene().removeCamera(this);
            while (this._rigCameras.length > 0) {
                var camera = this._rigCameras.pop();
                if (camera) {
                    camera.dispose();
                }
            }
            // Postprocesses
            if (this._rigPostProcess) {
                this._rigPostProcess.dispose(this);
                this._rigPostProcess = null;
                this._postProcesses = [];
            }
            else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
                this._rigPostProcess = null;
                this._postProcesses = [];
            }
            else {
                var i = this._postProcesses.length;
                while (--i >= 0) {
                    var postProcess = this._postProcesses[i];
                    if (postProcess) {
                        postProcess.dispose(this);
                    }
                }
            }
            // Render targets
            var i = this.customRenderTargets.length;
            while (--i >= 0) {
                this.customRenderTargets[i].dispose();
            }
            this.customRenderTargets = [];
            // Active Meshes
            this._activeMeshes.dispose();
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        Object.defineProperty(Camera.prototype, "leftCamera", {
            /**
             * Gets the left camera of a rig setup in case of Rigged Camera
             */
            get: function () {
                if (this._rigCameras.length < 1) {
                    return null;
                }
                return this._rigCameras[0];
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Camera.prototype, "rightCamera", {
            /**
             * Gets the right camera of a rig setup in case of Rigged Camera
             */
            get: function () {
                if (this._rigCameras.length < 2) {
                    return null;
                }
                return this._rigCameras[1];
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the left camera target of a rig setup in case of Rigged Camera
         * @returns the target position
         */
        Camera.prototype.getLeftTarget = function () {
            if (this._rigCameras.length < 1) {
                return null;
            }
            return this._rigCameras[0].getTarget();
        };
        /**
         * Gets the right camera target of a rig setup in case of Rigged Camera
         * @returns the target position
         */
        Camera.prototype.getRightTarget = function () {
            if (this._rigCameras.length < 2) {
                return null;
            }
            return this._rigCameras[1].getTarget();
        };
        /**
         * @hidden
         */
        Camera.prototype.setCameraRigMode = function (mode, rigParams) {
            if (this.cameraRigMode === mode) {
                return;
            }
            while (this._rigCameras.length > 0) {
                var camera = this._rigCameras.pop();
                if (camera) {
                    camera.dispose();
                }
            }
            this.cameraRigMode = mode;
            this._cameraRigParams = {};
            //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
            //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
            this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
            this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
            // create the rig cameras, unless none
            if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
                var leftCamera = this.createRigCamera(this.name + "_L", 0);
                var rightCamera = this.createRigCamera(this.name + "_R", 1);
                if (leftCamera && rightCamera) {
                    this._rigCameras.push(leftCamera);
                    this._rigCameras.push(rightCamera);
                }
            }
            switch (this.cameraRigMode) {
                case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                    this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
                    this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
                    break;
                case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                    var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
                    this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
                    this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
                    break;
                case Camera.RIG_MODE_VR:
                    var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
                    this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
                    this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
                    this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                    this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
                    this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
                    this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
                    this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
                    this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
                    this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                    this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
                    this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
                    this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
                    if (metrics.compensateDistortion) {
                        this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
                        this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
                    }
                    break;
                case Camera.RIG_MODE_WEBVR:
                    if (rigParams.vrDisplay) {
                        var leftEye = rigParams.vrDisplay.getEyeParameters('left');
                        var rightEye = rigParams.vrDisplay.getEyeParameters('right');
                        //Left eye
                        this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
                        this._rigCameras[0].setCameraRigParameter("left", true);
                        //leaving this for future reference
                        this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
                        this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
                        this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
                        this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
                        this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                        this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
                        this._rigCameras[0].parent = this;
                        this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
                        //Right eye
                        this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
                        this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
                        this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
                        this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
                        this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
                        this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
                        this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
                        this._rigCameras[1].parent = this;
                        this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
                        if (Camera.UseAlternateWebVRRendering) {
                            this._rigCameras[1]._skipRendering = true;
                            this._rigCameras[0]._alternateCamera = this._rigCameras[1];
                        }
                    }
                    break;
            }
            this._cascadePostProcessesToRigCams();
            this.update();
        };
        Camera.prototype._getVRProjectionMatrix = function () {
            BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
            this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
            return this._projectionMatrix;
        };
        Camera.prototype._updateCameraRotationMatrix = function () {
            //Here for WebVR
        };
        Camera.prototype._updateWebVRCameraRotationMatrix = function () {
            //Here for WebVR
        };
        /**
         * This function MUST be overwritten by the different WebVR cameras available.
         * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
         */
        Camera.prototype._getWebVRProjectionMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        /**
         * This function MUST be overwritten by the different WebVR cameras available.
         * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
         */
        Camera.prototype._getWebVRViewMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        /** @hidden */
        Camera.prototype.setCameraRigParameter = function (name, value) {
            if (!this._cameraRigParams) {
                this._cameraRigParams = {};
            }
            this._cameraRigParams[name] = value;
            //provisionnally:
            if (name === "interaxialDistance") {
                this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
            }
        };
        /**
         * needs to be overridden by children so sub has required properties to be copied
         * @hidden
         */
        Camera.prototype.createRigCamera = function (name, cameraIndex) {
            return null;
        };
        /**
         * May need to be overridden by children
         * @hidden
         */
        Camera.prototype._updateRigCameras = function () {
            for (var i = 0; i < this._rigCameras.length; i++) {
                this._rigCameras[i].minZ = this.minZ;
                this._rigCameras[i].maxZ = this.maxZ;
                this._rigCameras[i].fov = this.fov;
            }
            // only update viewport when ANAGLYPH
            if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
                this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
            }
        };
        /** @hidden */
        Camera.prototype._setupInputs = function () {
        };
        /**
         * Serialiaze the camera setup to a json represention
         * @returns the JSON representation
         */
        Camera.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            // Type
            serializationObject.type = this.getClassName();
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            if (this.inputs) {
                this.inputs.serialize(serializationObject);
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            serializationObject.ranges = this.serializeAnimationRanges();
            return serializationObject;
        };
        /**
         * Clones the current camera.
         * @param name The cloned camera name
         * @returns the cloned camera
         */
        Camera.prototype.clone = function (name) {
            return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
        };
        /**
         * Gets the direction of the camera relative to a given local axis.
         * @param localAxis Defines the reference axis to provide a relative direction.
         * @return the direction
         */
        Camera.prototype.getDirection = function (localAxis) {
            var result = BABYLON.Vector3.Zero();
            this.getDirectionToRef(localAxis, result);
            return result;
        };
        /**
         * Gets the direction of the camera relative to a given local axis into a passed vector.
         * @param localAxis Defines the reference axis to provide a relative direction.
         * @param result Defines the vector to store the result in
         */
        Camera.prototype.getDirectionToRef = function (localAxis, result) {
            BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
        };
        /**
         * Gets a camera constructor for a given camera type
         * @param type The type of the camera to construct (should be equal to one of the camera class name)
         * @param name The name of the camera the result will be able to instantiate
         * @param scene The scene the result will construct the camera in
         * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
         * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
         * @returns a factory method to construc the camera
         */
        Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
            if (interaxial_distance === void 0) { interaxial_distance = 0; }
            if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
            var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
                interaxial_distance: interaxial_distance,
                isStereoscopicSideBySide: isStereoscopicSideBySide
            });
            if (constructorFunc) {
                return constructorFunc;
            }
            // Default to universal camera
            return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
        };
        /**
         * Compute the world  matrix of the camera.
         * @returns the camera workd matrix
         */
        Camera.prototype.computeWorldMatrix = function () {
            return this.getWorldMatrix();
        };
        /**
         * Parse a JSON and creates the camera from the parsed information
         * @param parsedCamera The JSON to parse
         * @param scene The scene to instantiate the camera in
         * @returns the newly constructed camera
         */
        Camera.Parse = function (parsedCamera, scene) {
            var type = parsedCamera.type;
            var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
            var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
            // Parent
            if (parsedCamera.parentId) {
                camera._waitingParentId = parsedCamera.parentId;
            }
            //If camera has an input manager, let it parse inputs settings
            if (camera.inputs) {
                camera.inputs.parse(parsedCamera);
                camera._setupInputs();
            }
            if (camera.setPosition) { // need to force position
                camera.position.copyFromFloats(0, 0, 0);
                camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
            }
            // Target
            if (parsedCamera.target) {
                if (camera.setTarget) {
                    camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
                }
            }
            // Apply 3d rig, when found
            if (parsedCamera.cameraRigMode) {
                var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
                camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
            }
            // Animations
            if (parsedCamera.animations) {
                for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
                    var parsedAnimation = parsedCamera.animations[animationIndex];
                    camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
            }
            if (parsedCamera.autoAnimate) {
                scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
            }
            return camera;
        };
        /**
         * This is the default projection mode used by the cameras.
         * It helps recreating a feeling of perspective and better appreciate depth.
         * This is the best way to simulate real life cameras.
         */
        Camera.PERSPECTIVE_CAMERA = 0;
        /**
         * This helps creating camera with an orthographic mode.
         * Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
         */
        Camera.ORTHOGRAPHIC_CAMERA = 1;
        /**
         * This is the default FOV mode for perspective cameras.
         * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
         */
        Camera.FOVMODE_VERTICAL_FIXED = 0;
        /**
         * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
         */
        Camera.FOVMODE_HORIZONTAL_FIXED = 1;
        /**
         * This specifies ther is no need for a camera rig.
         * Basically only one eye is rendered corresponding to the camera.
         */
        Camera.RIG_MODE_NONE = 0;
        /**
         * Simulates a camera Rig with one blue eye and one red eye.
         * This can be use with 3d blue and red glasses.
         */
        Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
        /**
         * Defines that both eyes of the camera will be rendered side by side with a parallel target.
         */
        Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
        /**
         * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
         */
        Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
        /**
         * Defines that both eyes of the camera will be rendered over under each other.
         */
        Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
        /**
         * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
         */
        Camera.RIG_MODE_VR = 20;
        /**
         * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
         */
        Camera.RIG_MODE_WEBVR = 21;
        /**
         * Defines if by default attaching controls should prevent the default javascript event to continue.
         */
        Camera.ForceAttachControlToAlwaysPreventDefault = false;
        /**
         * @hidden
         * Might be removed once multiview will be a thing
         */
        Camera.UseAlternateWebVRRendering = false;
        __decorate([
            BABYLON.serializeAsVector3()
        ], Camera.prototype, "position", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], Camera.prototype, "upVector", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoLeft", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoRight", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoBottom", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "orthoTop", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "fov", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "minZ", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "maxZ", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "inertia", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "mode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "layerMask", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "fovMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "cameraRigMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "interaxialDistance", void 0);
        __decorate([
            BABYLON.serialize()
        ], Camera.prototype, "isStereoscopicSideBySide", void 0);
        return Camera;
    }(BABYLON.Node));
    BABYLON.Camera = Camera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.camera.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This is the manager responsible of all the rendering for meshes sprites and particles.
     * It is enable to manage the different groups as well as the different necessary sort functions.
     * This should not be used directly aside of the few static configurations
     */
    var RenderingManager = /** @class */ (function () {
        /**
         * Instantiates a new rendering group for a particular scene
         * @param scene Defines the scene the groups belongs to
         */
        function RenderingManager(scene) {
            /**
             * @hidden
             */
            this._useSceneAutoClearSetup = false;
            this._renderingGroups = new Array();
            this._autoClearDepthStencil = {};
            this._customOpaqueSortCompareFn = {};
            this._customAlphaTestSortCompareFn = {};
            this._customTransparentSortCompareFn = {};
            this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
            this._scene = scene;
            for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
                this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
            }
        }
        RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
            if (depth === void 0) { depth = true; }
            if (stencil === void 0) { stencil = true; }
            if (this._depthStencilBufferAlreadyCleaned) {
                return;
            }
            this._scene.getEngine().clear(null, false, depth, stencil);
            this._depthStencilBufferAlreadyCleaned = true;
        };
        /**
         * Renders the entire managed groups. This is used by the scene or the different rennder targets.
         * @hidden
         */
        RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
            // Update the observable context (not null as it only goes away on dispose)
            var info = this._renderingGroupInfo;
            info.scene = this._scene;
            info.camera = this._scene.activeCamera;
            // Dispatch sprites
            if (this._scene.spriteManagers && renderSprites) {
                for (var index = 0; index < this._scene.spriteManagers.length; index++) {
                    var manager = this._scene.spriteManagers[index];
                    this.dispatchSprites(manager);
                }
            }
            // Render
            for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
                this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
                var renderingGroup = this._renderingGroups[index];
                if (!renderingGroup) {
                    continue;
                }
                var renderingGroupMask = Math.pow(2, index);
                info.renderingGroupId = index;
                // Before Observable
                this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
                // Clear depth/stencil if needed
                if (RenderingManager.AUTOCLEAR) {
                    var autoClear = this._useSceneAutoClearSetup ?
                        this._scene.getAutoClearDepthStencilSetup(index) :
                        this._autoClearDepthStencil[index];
                    if (autoClear && autoClear.autoClear) {
                        this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
                    }
                }
                // Render
                for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
                    var step = _a[_i];
                    step.action(index);
                }
                renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
                for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
                    var step = _c[_b];
                    step.action(index);
                }
                // After Observable
                this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
            }
        };
        /**
         * Resets the different information of the group to prepare a new frame
         * @hidden
         */
        RenderingManager.prototype.reset = function () {
            for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
                var renderingGroup = this._renderingGroups[index];
                if (renderingGroup) {
                    renderingGroup.prepare();
                }
            }
        };
        /**
         * Dispose and release the group and its associated resources.
         * @hidden
         */
        RenderingManager.prototype.dispose = function () {
            this.freeRenderingGroups();
            this._renderingGroups.length = 0;
            this._renderingGroupInfo = null;
        };
        /**
         * Clear the info related to rendering groups preventing retention points during dispose.
         */
        RenderingManager.prototype.freeRenderingGroups = function () {
            for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
                var renderingGroup = this._renderingGroups[index];
                if (renderingGroup) {
                    renderingGroup.dispose();
                }
            }
        };
        RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
            if (this._renderingGroups[renderingGroupId] === undefined) {
                this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
            }
        };
        /**
         * Add a sprite manager to the rendering manager in order to render it this frame.
         * @param spriteManager Define the sprite manager to render
         */
        RenderingManager.prototype.dispatchSprites = function (spriteManager) {
            var renderingGroupId = spriteManager.renderingGroupId || 0;
            this._prepareRenderingGroup(renderingGroupId);
            this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
        };
        /**
         * Add a particle system to the rendering manager in order to render it this frame.
         * @param particleSystem Define the particle system to render
         */
        RenderingManager.prototype.dispatchParticles = function (particleSystem) {
            var renderingGroupId = particleSystem.renderingGroupId || 0;
            this._prepareRenderingGroup(renderingGroupId);
            this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
        };
        /**
         * Add a submesh to the manager in order to render it this frame
         * @param subMesh The submesh to dispatch
         * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
         * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
         */
        RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
            if (mesh === undefined) {
                mesh = subMesh.getMesh();
            }
            var renderingGroupId = mesh.renderingGroupId || 0;
            this._prepareRenderingGroup(renderingGroupId);
            this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
        };
        /**
         * Overrides the default sort function applied in the renderging group to prepare the meshes.
         * This allowed control for front to back rendering or reversly depending of the special needs.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
         * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
         * @param transparentSortCompareFn The transparent queue comparison function use to sort.
         */
        RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
            this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
            this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
            if (this._renderingGroups[renderingGroupId]) {
                var group = this._renderingGroups[renderingGroupId];
                group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
                group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
                group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
            }
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         * @param depth Automatically clears depth between groups if true and autoClear is true.
         * @param stencil Automatically clears stencil between groups if true and autoClear is true.
         */
        RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
            if (depth === void 0) { depth = true; }
            if (stencil === void 0) { stencil = true; }
            this._autoClearDepthStencil[renderingGroupId] = {
                autoClear: autoClearDepthStencil,
                depth: depth,
                stencil: stencil
            };
        };
        /**
         * Gets the current auto clear configuration for one rendering group of the rendering
         * manager.
         * @param index the rendering group index to get the information for
         * @returns The auto clear setup for the requested rendering group
         */
        RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
            return this._autoClearDepthStencil[index];
        };
        /**
         * The max id used for rendering groups (not included)
         */
        RenderingManager.MAX_RENDERINGGROUPS = 4;
        /**
         * The min id used for rendering groups (included)
         */
        RenderingManager.MIN_RENDERINGGROUPS = 0;
        /**
         * Used to globally prevent autoclearing scenes.
         */
        RenderingManager.AUTOCLEAR = true;
        return RenderingManager;
    }());
    BABYLON.RenderingManager = RenderingManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.renderingManager.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents the object necessary to create a rendering group.
     * This is exclusively used and created by the rendering manager.
     * To modify the behavior, you use the available helpers in your scene or meshes.
     * @hidden
     */
    var RenderingGroup = /** @class */ (function () {
        /**
         * Creates a new rendering group.
         * @param index The rendering group index
         * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
         * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
         * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
         */
        function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this.index = index;
            this._opaqueSubMeshes = new BABYLON.SmartArray(256);
            this._transparentSubMeshes = new BABYLON.SmartArray(256);
            this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
            this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
            this._particleSystems = new BABYLON.SmartArray(256);
            this._spriteManagers = new BABYLON.SmartArray(256);
            this._edgesRenderers = new BABYLON.SmartArray(16);
            this._scene = scene;
            this.opaqueSortCompareFn = opaqueSortCompareFn;
            this.alphaTestSortCompareFn = alphaTestSortCompareFn;
            this.transparentSortCompareFn = transparentSortCompareFn;
        }
        Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
            /**
             * Set the opaque sort comparison function.
             * If null the sub meshes will be render in the order they were created
             */
            set: function (value) {
                this._opaqueSortCompareFn = value;
                if (value) {
                    this._renderOpaque = this.renderOpaqueSorted;
                }
                else {
                    this._renderOpaque = RenderingGroup.renderUnsorted;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
            /**
             * Set the alpha test sort comparison function.
             * If null the sub meshes will be render in the order they were created
             */
            set: function (value) {
                this._alphaTestSortCompareFn = value;
                if (value) {
                    this._renderAlphaTest = this.renderAlphaTestSorted;
                }
                else {
                    this._renderAlphaTest = RenderingGroup.renderUnsorted;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
            /**
             * Set the transparent sort comparison function.
             * If null the sub meshes will be render in the order they were created
             */
            set: function (value) {
                if (value) {
                    this._transparentSortCompareFn = value;
                }
                else {
                    this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
                }
                this._renderTransparent = this.renderTransparentSorted;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Render all the sub meshes contained in the group.
         * @param customRenderFunction Used to override the default render behaviour of the group.
         * @returns true if rendered some submeshes.
         */
        RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
            if (customRenderFunction) {
                customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
                return;
            }
            var engine = this._scene.getEngine();
            // Depth only
            if (this._depthOnlySubMeshes.length !== 0) {
                engine.setColorWrite(false);
                this._renderAlphaTest(this._depthOnlySubMeshes);
                engine.setColorWrite(true);
            }
            // Opaque
            if (this._opaqueSubMeshes.length !== 0) {
                this._renderOpaque(this._opaqueSubMeshes);
            }
            // Alpha test
            if (this._alphaTestSubMeshes.length !== 0) {
                this._renderAlphaTest(this._alphaTestSubMeshes);
            }
            var stencilState = engine.getStencilBuffer();
            engine.setStencilBuffer(false);
            // Sprites
            if (renderSprites) {
                this._renderSprites();
            }
            // Particles
            if (renderParticles) {
                this._renderParticles(activeMeshes);
            }
            if (this.onBeforeTransparentRendering) {
                this.onBeforeTransparentRendering();
            }
            // Transparent
            if (this._transparentSubMeshes.length !== 0) {
                this._renderTransparent(this._transparentSubMeshes);
                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            }
            // Set back stencil to false in case it changes before the edge renderer.
            engine.setStencilBuffer(false);
            // Edges
            if (this._edgesRenderers.length) {
                for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
                    this._edgesRenderers.data[edgesRendererIndex].render();
                }
                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            }
            // Restore Stencil state.
            engine.setStencilBuffer(stencilState);
        };
        /**
         * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
            return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
        };
        /**
         * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
            return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
        };
        /**
         * Renders the opaque submeshes in the order from the transparentSortCompareFn.
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
            return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
        };
        /**
         * Renders the submeshes in a specified order.
         * @param subMeshes The submeshes to sort before render
         * @param sortCompareFn The comparison function use to sort
         * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
         * @param transparent Specifies to activate blending if true
         */
        RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
            var subIndex = 0;
            var subMesh;
            var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
            for (; subIndex < subMeshes.length; subIndex++) {
                subMesh = subMeshes.data[subIndex];
                subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
                subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
            }
            var sortedArray = subMeshes.data.slice(0, subMeshes.length);
            if (sortCompareFn) {
                sortedArray.sort(sortCompareFn);
            }
            for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
                subMesh = sortedArray[subIndex];
                if (transparent) {
                    var material = subMesh.getMaterial();
                    if (material && material.needDepthPrePass) {
                        var engine = material.getScene().getEngine();
                        engine.setColorWrite(false);
                        engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
                        subMesh.render(false);
                        engine.setColorWrite(true);
                    }
                }
                subMesh.render(transparent);
            }
        };
        /**
         * Renders the submeshes in the order they were dispatched (no sort applied).
         * @param subMeshes The submeshes to render
         */
        RenderingGroup.renderUnsorted = function (subMeshes) {
            for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
                var submesh = subMeshes.data[subIndex];
                submesh.render(false);
            }
        };
        /**
         * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
         * are rendered back to front if in the same alpha index.
         *
         * @param a The first submesh
         * @param b The second submesh
         * @returns The result of the comparison
         */
        RenderingGroup.defaultTransparentSortCompare = function (a, b) {
            // Alpha index first
            if (a._alphaIndex > b._alphaIndex) {
                return 1;
            }
            if (a._alphaIndex < b._alphaIndex) {
                return -1;
            }
            // Then distance to camera
            return RenderingGroup.backToFrontSortCompare(a, b);
        };
        /**
         * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
         * are rendered back to front.
         *
         * @param a The first submesh
         * @param b The second submesh
         * @returns The result of the comparison
         */
        RenderingGroup.backToFrontSortCompare = function (a, b) {
            // Then distance to camera
            if (a._distanceToCamera < b._distanceToCamera) {
                return 1;
            }
            if (a._distanceToCamera > b._distanceToCamera) {
                return -1;
            }
            return 0;
        };
        /**
         * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
         * are rendered front to back (prevent overdraw).
         *
         * @param a The first submesh
         * @param b The second submesh
         * @returns The result of the comparison
         */
        RenderingGroup.frontToBackSortCompare = function (a, b) {
            // Then distance to camera
            if (a._distanceToCamera < b._distanceToCamera) {
                return -1;
            }
            if (a._distanceToCamera > b._distanceToCamera) {
                return 1;
            }
            return 0;
        };
        /**
         * Resets the different lists of submeshes to prepare a new frame.
         */
        RenderingGroup.prototype.prepare = function () {
            this._opaqueSubMeshes.reset();
            this._transparentSubMeshes.reset();
            this._alphaTestSubMeshes.reset();
            this._depthOnlySubMeshes.reset();
            this._particleSystems.reset();
            this._spriteManagers.reset();
            this._edgesRenderers.reset();
        };
        RenderingGroup.prototype.dispose = function () {
            this._opaqueSubMeshes.dispose();
            this._transparentSubMeshes.dispose();
            this._alphaTestSubMeshes.dispose();
            this._depthOnlySubMeshes.dispose();
            this._particleSystems.dispose();
            this._spriteManagers.dispose();
            this._edgesRenderers.dispose();
        };
        /**
         * Inserts the submesh in its correct queue depending on its material.
         * @param subMesh The submesh to dispatch
         * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
         * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
         */
        RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
            // Get mesh and materials if not provided
            if (mesh === undefined) {
                mesh = subMesh.getMesh();
            }
            if (material === undefined) {
                material = subMesh.getMaterial();
            }
            if (material === null || material === undefined) {
                return;
            }
            if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
                this._transparentSubMeshes.push(subMesh);
            }
            else if (material.needAlphaTesting()) { // Alpha test
                if (material.needDepthPrePass) {
                    this._depthOnlySubMeshes.push(subMesh);
                }
                this._alphaTestSubMeshes.push(subMesh);
            }
            else {
                if (material.needDepthPrePass) {
                    this._depthOnlySubMeshes.push(subMesh);
                }
                this._opaqueSubMeshes.push(subMesh); // Opaque
            }
            if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
                this._edgesRenderers.push(mesh._edgesRenderer);
            }
        };
        RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
            this._spriteManagers.push(spriteManager);
        };
        RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
            this._particleSystems.push(particleSystem);
        };
        RenderingGroup.prototype._renderParticles = function (activeMeshes) {
            if (this._particleSystems.length === 0) {
                return;
            }
            // Particles
            var activeCamera = this._scene.activeCamera;
            this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
            for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
                var particleSystem = this._particleSystems.data[particleIndex];
                if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
                    continue;
                }
                var emitter = particleSystem.emitter;
                if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
                    this._scene._activeParticles.addCount(particleSystem.render(), false);
                }
            }
            this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
        };
        RenderingGroup.prototype._renderSprites = function () {
            if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
                return;
            }
            // Sprites
            var activeCamera = this._scene.activeCamera;
            this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
            for (var id = 0; id < this._spriteManagers.length; id++) {
                var spriteManager = this._spriteManagers.data[id];
                if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
                    spriteManager.render();
                }
            }
            this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
        };
        return RenderingGroup;
    }());
    BABYLON.RenderingGroup = RenderingGroup;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.renderingGroup.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Groups all the scene component constants in one place to ease maintenance.
     * @hidden
     */
    var SceneComponentConstants = /** @class */ (function () {
        function SceneComponentConstants() {
        }
        SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
        SceneComponentConstants.NAME_LAYER = "Layer";
        SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
        SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
        SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
        SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
        SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
        SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
        SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
        SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
        SceneComponentConstants.NAME_SPRITE = "Sprite";
        SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
        SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
        SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
        SceneComponentConstants.NAME_OCTREE = "Octree";
        SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
        SceneComponentConstants.NAME_AUDIO = "Audio";
        SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
        SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
        SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
        SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
        SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
        SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
        SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
        SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
        SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
        SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
        SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
        SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
        SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
        SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
        SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
        SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
        SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
        SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
        SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
        SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
        SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
        SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
        SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
        SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
        SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
        SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
        SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
        return SceneComponentConstants;
    }());
    BABYLON.SceneComponentConstants = SceneComponentConstants;
    /**
     * Repressentation of a stage in the scene (Basically a list of ordered steps)
     * @hidden
     */
    var Stage = /** @class */ (function (_super) {
        __extends(Stage, _super);
        /**
         * Hide ctor from the rest of the world.
         * @param items The items to add.
         */
        function Stage(items) {
            return _super.apply(this, items) || this;
        }
        /**
         * Creates a new Stage.
         * @returns A new instance of a Stage
         */
        Stage.Create = function () {
            return Object.create(Stage.prototype);
        };
        /**
         * Registers a step in an ordered way in the targeted stage.
         * @param index Defines the position to register the step in
         * @param component Defines the component attached to the step
         * @param action Defines the action to launch during the step
         */
        Stage.prototype.registerStep = function (index, component, action) {
            var i = 0;
            var maxIndex = Number.MAX_VALUE;
            for (; i < this.length; i++) {
                var step = this[i];
                maxIndex = step.index;
                if (index < maxIndex) {
                    break;
                }
            }
            this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
        };
        /**
         * Clears all the steps from the stage.
         */
        Stage.prototype.clear = function () {
            this.length = 0;
        };
        return Stage;
    }(Array));
    BABYLON.Stage = Stage;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Base class of the scene acting as a container for the different elements composing a scene.
     * This class is dynamically extended by the different components of the scene increasing
     * flexibility and reducing coupling
     */
    var AbstractScene = /** @class */ (function () {
        function AbstractScene() {
            /**
             * Gets the list of root nodes (ie. nodes with no parent)
             */
            this.rootNodes = new Array();
            /** All of the cameras added to this scene
             * @see http://doc.babylonjs.com/babylon101/cameras
             */
            this.cameras = new Array();
            /**
            * All of the lights added to this scene
            * @see http://doc.babylonjs.com/babylon101/lights
            */
            this.lights = new Array();
            /**
            * All of the (abstract) meshes added to this scene
            */
            this.meshes = new Array();
            /**
             * The list of skeletons added to the scene
             * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
             */
            this.skeletons = new Array();
            /**
            * All of the particle systems added to this scene
            * @see http://doc.babylonjs.com/babylon101/particles
            */
            this.particleSystems = new Array();
            /**
             * Gets a list of Animations associated with the scene
             */
            this.animations = [];
            /**
            * All of the animation groups added to this scene
            * @see http://doc.babylonjs.com/how_to/group
            */
            this.animationGroups = new Array();
            /**
            * All of the multi-materials added to this scene
            * @see http://doc.babylonjs.com/how_to/multi_materials
            */
            this.multiMaterials = new Array();
            /**
            * All of the materials added to this scene
            * @see http://doc.babylonjs.com/babylon101/materials
            */
            this.materials = new Array();
            /**
             * The list of morph target managers added to the scene
             * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
             */
            this.morphTargetManagers = new Array();
            /**
             * The list of geometries used in the scene.
             */
            this.geometries = new Array();
            /**
            * All of the tranform nodes added to this scene
            * @see http://doc.babylonjs.com/how_to/transformnode
            */
            this.transformNodes = new Array();
            /**
             * ActionManagers available on the scene.
             */
            this.actionManagers = new Array();
            /**
             * Textures to keep.
             */
            this.textures = new Array();
        }
        /**
         * Adds a parser in the list of available ones
         * @param name Defines the name of the parser
         * @param parser Defines the parser to add
         */
        AbstractScene.AddParser = function (name, parser) {
            this._BabylonFileParsers[name] = parser;
        };
        /**
         * Gets a general parser from the list of avaialble ones
         * @param name Defines the name of the parser
         * @returns the requested parser or null
         */
        AbstractScene.GetParser = function (name) {
            if (this._BabylonFileParsers[name]) {
                return this._BabylonFileParsers[name];
            }
            return null;
        };
        /**
         * Adds n individual parser in the list of available ones
         * @param name Defines the name of the parser
         * @param parser Defines the parser to add
         */
        AbstractScene.AddIndividualParser = function (name, parser) {
            this._IndividualBabylonFileParsers[name] = parser;
        };
        /**
         * Gets an individual parser from the list of avaialble ones
         * @param name Defines the name of the parser
         * @returns the requested parser or null
         */
        AbstractScene.GetIndividualParser = function (name) {
            if (this._IndividualBabylonFileParsers[name]) {
                return this._IndividualBabylonFileParsers[name];
            }
            return null;
        };
        /**
         * Parser json data and populate both a scene and its associated container object
         * @param jsonData Defines the data to parse
         * @param scene Defines the scene to parse the data for
         * @param container Defines the container attached to the parsing sequence
         * @param rootUrl Defines the root url of the data
         */
        AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
            for (var parserName in this._BabylonFileParsers) {
                if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
                    this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
                }
            }
        };
        /**
         * Stores the list of available parsers in the application.
         */
        AbstractScene._BabylonFileParsers = {};
        /**
         * Stores the list of available individual parsers in the application.
         */
        AbstractScene._IndividualBabylonFileParsers = {};
        return AbstractScene;
    }());
    BABYLON.AbstractScene = AbstractScene;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.abstractScene.js.map


var BABYLON;
(function (BABYLON) {
    /** @hidden */
    var ClickInfo = /** @class */ (function () {
        function ClickInfo() {
            this._singleClick = false;
            this._doubleClick = false;
            this._hasSwiped = false;
            this._ignore = false;
        }
        Object.defineProperty(ClickInfo.prototype, "singleClick", {
            get: function () {
                return this._singleClick;
            },
            set: function (b) {
                this._singleClick = b;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ClickInfo.prototype, "doubleClick", {
            get: function () {
                return this._doubleClick;
            },
            set: function (b) {
                this._doubleClick = b;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
            get: function () {
                return this._hasSwiped;
            },
            set: function (b) {
                this._hasSwiped = b;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ClickInfo.prototype, "ignore", {
            get: function () {
                return this._ignore;
            },
            set: function (b) {
                this._ignore = b;
            },
            enumerable: true,
            configurable: true
        });
        return ClickInfo;
    }());
    /**
     * This class is used by the onRenderingGroupObservable
     */
    var RenderingGroupInfo = /** @class */ (function () {
        function RenderingGroupInfo() {
        }
        return RenderingGroupInfo;
    }());
    BABYLON.RenderingGroupInfo = RenderingGroupInfo;
    /**
     * Represents a scene to be rendered by the engine.
     * @see http://doc.babylonjs.com/features/scene
     */
    var Scene = /** @class */ (function (_super) {
        __extends(Scene, _super);
        /**
         * Creates a new Scene
         * @param engine defines the engine to use to render this scene
         */
        function Scene(engine) {
            var _this = _super.call(this) || this;
            // Members
            /**
             * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
             */
            _this.autoClear = true;
            /**
             * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
             */
            _this.autoClearDepthAndStencil = true;
            /**
             * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
             */
            _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
            /**
             * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
             */
            _this.ambientColor = new BABYLON.Color3(0, 0, 0);
            _this._forceWireframe = false;
            _this._forcePointsCloud = false;
            /**
             * Gets or sets a boolean indicating if animations are enabled
             */
            _this.animationsEnabled = true;
            _this._animationPropertiesOverride = null;
            /**
             * Gets or sets a boolean indicating if a constant deltatime has to be used
             * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
             */
            _this.useConstantAnimationDeltaTime = false;
            /**
             * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
             * Please note that it requires to run a ray cast through the scene on every frame
             */
            _this.constantlyUpdateMeshUnderPointer = false;
            /**
             * Defines the HTML cursor to use when hovering over interactive elements
             */
            _this.hoverCursor = "pointer";
            /**
             * Defines the HTML default cursor to use (empty by default)
             */
            _this.defaultCursor = "";
            /**
             * This is used to call preventDefault() on pointer down
             * in order to block unwanted artifacts like system double clicks
             */
            _this.preventDefaultOnPointerDown = true;
            // Metadata
            /**
             * Gets or sets user defined metadata
             */
            _this.metadata = null;
            /**
             * Use this array to add regular expressions used to disable offline support for specific urls
             */
            _this.disableOfflineSupportExceptionRules = new Array();
            /**
            * An event triggered when the scene is disposed.
            */
            _this.onDisposeObservable = new BABYLON.Observable();
            _this._onDisposeObserver = null;
            /**
            * An event triggered before rendering the scene (right after animations and physics)
            */
            _this.onBeforeRenderObservable = new BABYLON.Observable();
            _this._onBeforeRenderObserver = null;
            /**
            * An event triggered after rendering the scene
            */
            _this.onAfterRenderObservable = new BABYLON.Observable();
            _this._onAfterRenderObserver = null;
            /**
            * An event triggered before animating the scene
            */
            _this.onBeforeAnimationsObservable = new BABYLON.Observable();
            /**
            * An event triggered after animations processing
            */
            _this.onAfterAnimationsObservable = new BABYLON.Observable();
            /**
            * An event triggered before draw calls are ready to be sent
            */
            _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
            /**
            * An event triggered after draw calls have been sent
            */
            _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
            /**
            * An event triggered when the scene is ready
            */
            _this.onReadyObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering a camera
            */
            _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
            _this._onBeforeCameraRenderObserver = null;
            /**
            * An event triggered after rendering a camera
            */
            _this.onAfterCameraRenderObservable = new BABYLON.Observable();
            _this._onAfterCameraRenderObserver = null;
            /**
            * An event triggered when active meshes evaluation is about to start
            */
            _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
            /**
            * An event triggered when active meshes evaluation is done
            */
            _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
            /**
            * An event triggered when particles rendering is about to start
            * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
            */
            _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
            /**
            * An event triggered when particles rendering is done
            * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
            */
            _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
            /**
            * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
            */
            _this.onDataLoadedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a camera is created
            */
            _this.onNewCameraAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a camera is removed
            */
            _this.onCameraRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a light is created
            */
            _this.onNewLightAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a light is removed
            */
            _this.onLightRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a geometry is created
            */
            _this.onNewGeometryAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a geometry is removed
            */
            _this.onGeometryRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a transform node is created
            */
            _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a transform node is removed
            */
            _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a mesh is created
            */
            _this.onNewMeshAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a mesh is removed
            */
            _this.onMeshRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a material is created
            */
            _this.onNewMaterialAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a material is removed
            */
            _this.onMaterialRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a texture is created
            */
            _this.onNewTextureAddedObservable = new BABYLON.Observable();
            /**
            * An event triggered when a texture is removed
            */
            _this.onTextureRemovedObservable = new BABYLON.Observable();
            /**
            * An event triggered when render targets are about to be rendered
            * Can happen multiple times per frame.
            */
            _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered when render targets were rendered.
            * Can happen multiple times per frame.
            */
            _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered before calculating deterministic simulation step
            */
            _this.onBeforeStepObservable = new BABYLON.Observable();
            /**
            * An event triggered after calculating deterministic simulation step
            */
            _this.onAfterStepObservable = new BABYLON.Observable();
            /**
             * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
             * The RenderinGroupInfo class contains all the information about the context in which the observable is called
             * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
             */
            _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
            /**
             * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
             * The RenderinGroupInfo class contains all the information about the context in which the observable is called
             * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
             */
            _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
            /**
             * This Observable will when a mesh has been imported into the scene.
             */
            _this.onMeshImportedObservable = new BABYLON.Observable();
            // Animations
            _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
            /**
             * This observable event is triggered when any ponter event is triggered. It is registered during Scene.attachControl() and it is called BEFORE the 3D engine process anything (mesh/sprite picking for instance).
             * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
             */
            _this.onPrePointerObservable = new BABYLON.Observable();
            /**
             * Observable event triggered each time an input event is received from the rendering canvas
             */
            _this.onPointerObservable = new BABYLON.Observable();
            _this._meshPickProceed = false;
            _this._currentPickResult = null;
            _this._previousPickResult = null;
            _this._totalPointersPressed = 0;
            _this._doubleClickOccured = false;
            /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
            _this.cameraToUseForPointers = null;
            _this._pointerX = 0;
            _this._pointerY = 0;
            _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
            _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
            _this._startingPointerTime = 0;
            _this._previousStartingPointerTime = 0;
            _this._pointerCaptures = {};
            // Deterministic lockstep
            _this._timeAccumulator = 0;
            _this._currentStepId = 0;
            _this._currentInternalStep = 0;
            // Keyboard
            /**
             * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
             * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
             */
            _this.onPreKeyboardObservable = new BABYLON.Observable();
            /**
             * Observable event triggered each time an keyboard event is received from the hosting window
             */
            _this.onKeyboardObservable = new BABYLON.Observable();
            // Coordinates system
            _this._useRightHandedSystem = false;
            // Fog
            _this._fogEnabled = true;
            _this._fogMode = Scene.FOGMODE_NONE;
            /**
            * Gets or sets the fog color to use
            * @see http://doc.babylonjs.com/babylon101/environment#fog
            * (Default is Color3(0.2, 0.2, 0.3))
            */
            _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
            /**
            * Gets or sets the fog density to use
            * @see http://doc.babylonjs.com/babylon101/environment#fog
            * (Default is 0.1)
            */
            _this.fogDensity = 0.1;
            /**
            * Gets or sets the fog start distance to use
            * @see http://doc.babylonjs.com/babylon101/environment#fog
            * (Default is 0)
            */
            _this.fogStart = 0;
            /**
            * Gets or sets the fog end distance to use
            * @see http://doc.babylonjs.com/babylon101/environment#fog
            * (Default is 1000)
            */
            _this.fogEnd = 1000.0;
            // Lights
            _this._shadowsEnabled = true;
            _this._lightsEnabled = true;
            /** All of the active cameras added to this scene. */
            _this.activeCameras = new Array();
            // Textures
            _this._texturesEnabled = true;
            // Particles
            /**
            * Gets or sets a boolean indicating if particles are enabled on this scene
            */
            _this.particlesEnabled = true;
            // Sprites
            /**
            * Gets or sets a boolean indicating if sprites are enabled on this scene
            */
            _this.spritesEnabled = true;
            // Skeletons
            _this._skeletonsEnabled = true;
            // Lens flares
            /**
            * Gets or sets a boolean indicating if lens flares are enabled on this scene
            */
            _this.lensFlaresEnabled = true;
            // Collisions
            /**
            * Gets or sets a boolean indicating if collisions are enabled on this scene
            * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
            */
            _this.collisionsEnabled = true;
            /**
             * Defines the gravity applied to this scene (used only for collisions)
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
             */
            _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
            // Postprocesses
            /**
            * Gets or sets a boolean indicating if postprocesses are enabled on this scene
            */
            _this.postProcessesEnabled = true;
            /**
             * The list of postprocesses added to the scene
             */
            _this.postProcesses = new Array();
            // Customs render targets
            /**
            * Gets or sets a boolean indicating if render targets are enabled on this scene
            */
            _this.renderTargetsEnabled = true;
            /**
            * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
            * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
            */
            _this.dumpNextRenderTargets = false;
            /**
             * The list of user defined render targets added to the scene
             */
            _this.customRenderTargets = new Array();
            /**
             * Gets the list of meshes imported to the scene through SceneLoader
             */
            _this.importedMeshesFiles = new Array();
            // Probes
            /**
            * Gets or sets a boolean indicating if probes are enabled on this scene
            */
            _this.probesEnabled = true;
            _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
            // Procedural textures
            /**
            * Gets or sets a boolean indicating if procedural textures are enabled on this scene
            */
            _this.proceduralTexturesEnabled = true;
            // Performance counters
            _this._totalVertices = new BABYLON.PerfCounter();
            /** @hidden */
            _this._activeIndices = new BABYLON.PerfCounter();
            /** @hidden */
            _this._activeParticles = new BABYLON.PerfCounter();
            /** @hidden */
            _this._activeBones = new BABYLON.PerfCounter();
            _this._animationTime = 0;
            /**
             * Gets or sets a general scale for animation speed
             * @see https://www.babylonjs-playground.com/#IBU2W7#3
             */
            _this.animationTimeScale = 1;
            _this._renderId = 0;
            _this._frameId = 0;
            _this._executeWhenReadyTimeoutId = -1;
            _this._intermediateRendering = false;
            _this._viewUpdateFlag = -1;
            _this._projectionUpdateFlag = -1;
            _this._alternateViewUpdateFlag = -1;
            _this._alternateProjectionUpdateFlag = -1;
            /** @hidden */
            _this._toBeDisposed = new Array(256);
            _this._activeRequests = new Array();
            _this._pendingData = new Array();
            _this._isDisposed = false;
            /**
             * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
             * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
             */
            _this.dispatchAllSubMeshesOfActiveMeshes = false;
            _this._activeMeshes = new BABYLON.SmartArray(256);
            _this._processedMaterials = new BABYLON.SmartArray(256);
            _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
            /** @hidden */
            _this._activeParticleSystems = new BABYLON.SmartArray(256);
            _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
            _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
            /** @hidden */
            _this._activeAnimatables = new Array();
            _this._transformMatrix = BABYLON.Matrix.Zero();
            _this._useAlternateCameraConfiguration = false;
            _this._alternateRendering = false;
            /**
             * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
             * This is useful if there are more lights that the maximum simulteanous authorized
             */
            _this.requireLightSorting = false;
            /**
             * @hidden
             * Backing store of defined scene components.
             */
            _this._components = [];
            /**
             * @hidden
             * Backing store of defined scene components.
             */
            _this._serializableComponents = [];
            /**
             * List of components to register on the next registration step.
             */
            _this._transientComponents = [];
            /**
             * @hidden
             * Defines the actions happening before camera updates.
             */
            _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening before clear the canvas.
             */
            _this._beforeClearStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions when collecting render targets for the frame.
             */
            _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening for one camera in the frame.
             */
            _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening during the per mesh ready checks.
             */
            _this._isReadyForMeshStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening before evaluate active mesh checks.
             */
            _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening during the evaluate sub mesh checks.
             */
            _this._evaluateSubMeshStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening during the active mesh stage.
             */
            _this._activeMeshStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening during the per camera render target step.
             */
            _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just before the active camera is drawing.
             */
            _this._beforeCameraDrawStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just before a rendering group is drawing.
             */
            _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just before a mesh is drawing.
             */
            _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just after a mesh has been drawn.
             */
            _this._afterRenderingMeshStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just after a rendering group has been drawn.
             */
            _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just after the active camera has been drawn.
             */
            _this._afterCameraDrawStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening just after rendering all cameras and computing intersections.
             */
            _this._afterRenderStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening when a pointer move event happens.
             */
            _this._pointerMoveStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening when a pointer down event happens.
             */
            _this._pointerDownStage = BABYLON.Stage.Create();
            /**
             * @hidden
             * Defines the actions happening when a pointer up event happens.
             */
            _this._pointerUpStage = BABYLON.Stage.Create();
            _this._defaultMeshCandidates = {
                data: [],
                length: 0
            };
            _this._defaultSubMeshCandidates = {
                data: [],
                length: 0
            };
            _this._activeMeshesFrozen = false;
            /** @hidden */
            _this._allowPostProcessClearColor = true;
            /**
             * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
             */
            _this.getDeterministicFrameTime = function () {
                return 1000.0 / 60.0; // frame time in ms
            };
            _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
            _this._blockMaterialDirtyMechanism = false;
            _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
            _this._engine.scenes.push(_this);
            _this._uid = null;
            _this._renderingManager = new BABYLON.RenderingManager(_this);
            if (BABYLON.PostProcessManager) {
                _this.postProcessManager = new BABYLON.PostProcessManager(_this);
            }
            if (BABYLON.Tools.IsWindowObjectExist()) {
                _this.attachControl();
            }
            //collision coordinator initialization. For now legacy per default.
            _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
            // Uniform Buffer
            _this._createUbo();
            // Default Image processing definition
            if (BABYLON.ImageProcessingConfiguration) {
                _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
            }
            _this.setDefaultCandidateProviders();
            return _this;
        }
        Object.defineProperty(Scene.prototype, "environmentTexture", {
            /**
             * Texture used in all pbr material as the reflection texture.
             * As in the majority of the scene they are the same (exception for multi room and so on),
             * this is easier to reference from here than from all the materials.
             */
            get: function () {
                return this._environmentTexture;
            },
            /**
             * Texture used in all pbr material as the reflection texture.
             * As in the majority of the scene they are the same (exception for multi room and so on),
             * this is easier to set here than in all the materials.
             */
            set: function (value) {
                if (this._environmentTexture === value) {
                    return;
                }
                this._environmentTexture = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
            /**
             * Default image processing configuration used either in the rendering
             * Forward main pass or through the imageProcessingPostProcess if present.
             * As in the majority of the scene they are the same (exception for multi camera),
             * this is easier to reference from here than from all the materials and post process.
             *
             * No setter as we it is a shared configuration, you can set the values instead.
             */
            get: function () {
                return this._imageProcessingConfiguration;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "forceWireframe", {
            get: function () {
                return this._forceWireframe;
            },
            /**
             * Gets or sets a boolean indicating if all rendering must be done in wireframe
             */
            set: function (value) {
                if (this._forceWireframe === value) {
                    return;
                }
                this._forceWireframe = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "forcePointsCloud", {
            get: function () {
                return this._forcePointsCloud;
            },
            /**
             * Gets or sets a boolean indicating if all rendering must be done in point cloud
             */
            set: function (value) {
                if (this._forcePointsCloud === value) {
                    return;
                }
                this._forcePointsCloud = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
            /**
             * Gets or sets the animation properties override
             */
            get: function () {
                return this._animationPropertiesOverride;
            },
            set: function (value) {
                this._animationPropertiesOverride = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "onDispose", {
            /** Sets a function to be executed when this scene is disposed. */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "beforeRender", {
            /** Sets a function to be executed before rendering this scene */
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                if (callback) {
                    this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "afterRender", {
            /** Sets a function to be executed after rendering this scene */
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                if (callback) {
                    this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "beforeCameraRender", {
            /** Sets a function to be executed before rendering a camera*/
            set: function (callback) {
                if (this._onBeforeCameraRenderObserver) {
                    this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
                }
                this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "afterCameraRender", {
            /** Sets a function to be executed after rendering a camera*/
            set: function (callback) {
                if (this._onAfterCameraRenderObserver) {
                    this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
                }
                this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
            /**
             * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
             */
            get: function () {
                return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
            get: function () {
                return this._useRightHandedSystem;
            },
            /**
            * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
            */
            set: function (value) {
                if (this._useRightHandedSystem === value) {
                    return;
                }
                this._useRightHandedSystem = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Sets the step Id used by deterministic lock step
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         * @param newStepId defines the step Id
         */
        Scene.prototype.setStepId = function (newStepId) {
            this._currentStepId = newStepId;
        };
        /**
         * Gets the step Id used by deterministic lock step
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         * @returns the step Id
         */
        Scene.prototype.getStepId = function () {
            return this._currentStepId;
        };
        /**
         * Gets the internal step used by deterministic lock step
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         * @returns the internal step
         */
        Scene.prototype.getInternalStep = function () {
            return this._currentInternalStep;
        };
        Object.defineProperty(Scene.prototype, "fogEnabled", {
            get: function () {
                return this._fogEnabled;
            },
            /**
            * Gets or sets a boolean indicating if fog is enabled on this scene
            * @see http://doc.babylonjs.com/babylon101/environment#fog
            * (Default is true)
            */
            set: function (value) {
                if (this._fogEnabled === value) {
                    return;
                }
                this._fogEnabled = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "fogMode", {
            get: function () {
                return this._fogMode;
            },
            /**
            * Gets or sets the fog mode to use
            * @see http://doc.babylonjs.com/babylon101/environment#fog
            * | mode | value |
            * | --- | --- |
            * | FOGMODE_NONE | 0 |
            * | FOGMODE_EXP | 1 |
            * | FOGMODE_EXP2 | 2 |
            * | FOGMODE_LINEAR | 3 |
            */
            set: function (value) {
                if (this._fogMode === value) {
                    return;
                }
                this._fogMode = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "shadowsEnabled", {
            get: function () {
                return this._shadowsEnabled;
            },
            /**
            * Gets or sets a boolean indicating if shadows are enabled on this scene
            */
            set: function (value) {
                if (this._shadowsEnabled === value) {
                    return;
                }
                this._shadowsEnabled = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "lightsEnabled", {
            get: function () {
                return this._lightsEnabled;
            },
            /**
            * Gets or sets a boolean indicating if lights are enabled on this scene
            */
            set: function (value) {
                if (this._lightsEnabled === value) {
                    return;
                }
                this._lightsEnabled = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "defaultMaterial", {
            /** The default material used on meshes when no material is affected */
            get: function () {
                if (!this._defaultMaterial) {
                    this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
                }
                return this._defaultMaterial;
            },
            /** The default material used on meshes when no material is affected */
            set: function (value) {
                this._defaultMaterial = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "texturesEnabled", {
            get: function () {
                return this._texturesEnabled;
            },
            /**
            * Gets or sets a boolean indicating if textures are enabled on this scene
            */
            set: function (value) {
                if (this._texturesEnabled === value) {
                    return;
                }
                this._texturesEnabled = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
            get: function () {
                return this._skeletonsEnabled;
            },
            /**
            * Gets or sets a boolean indicating if skeletons are enabled on this scene
            */
            set: function (value) {
                if (this._skeletonsEnabled === value) {
                    return;
                }
                this._skeletonsEnabled = value;
                this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
            /** @hidden */
            get: function () {
                return this._alternateRendering;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "frustumPlanes", {
            /**
             * Gets the list of frustum planes (built from the active camera)
             */
            get: function () {
                return this._frustumPlanes;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Registers the transient components if needed.
         */
        Scene.prototype._registerTransientComponents = function () {
            // Register components that have been associated lately to the scene.
            if (this._transientComponents.length > 0) {
                for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
                    var component = _a[_i];
                    component.register();
                }
                this._transientComponents = [];
            }
        };
        /**
         * @hidden
         * Add a component to the scene.
         * Note that the ccomponent could be registered on th next frame if this is called after
         * the register component stage.
         * @param component Defines the component to add to the scene
         */
        Scene.prototype._addComponent = function (component) {
            this._components.push(component);
            this._transientComponents.push(component);
            var serializableComponent = component;
            if (serializableComponent.addFromContainer) {
                this._serializableComponents.push(serializableComponent);
            }
        };
        /**
         * @hidden
         * Gets a component from the scene.
         * @param name defines the name of the component to retrieve
         * @returns the component or null if not present
         */
        Scene.prototype._getComponent = function (name) {
            for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
                var component = _a[_i];
                if (component.name === name) {
                    return component;
                }
            }
            return null;
        };
        /**
         * @hidden
         */
        Scene.prototype._getDefaultMeshCandidates = function () {
            this._defaultMeshCandidates.data = this.meshes;
            this._defaultMeshCandidates.length = this.meshes.length;
            return this._defaultMeshCandidates;
        };
        /**
         * @hidden
         */
        Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
            this._defaultSubMeshCandidates.data = mesh.subMeshes;
            this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
            return this._defaultSubMeshCandidates;
        };
        /**
         * Sets the default candidate providers for the scene.
         * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
         * and getCollidingSubMeshCandidates to their default function
         */
        Scene.prototype.setDefaultCandidateProviders = function () {
            this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
            this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
            this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
            this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
        };
        Object.defineProperty(Scene.prototype, "workerCollisions", {
            /**
             * Gets a boolean indicating if collisions are processed on a web worker
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
             */
            get: function () {
                return this._workerCollisions;
            },
            set: function (enabled) {
                if (!BABYLON.CollisionCoordinatorLegacy) {
                    return;
                }
                enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
                this._workerCollisions = enabled;
                if (this.collisionCoordinator) {
                    this.collisionCoordinator.destroy();
                }
                this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
                this.collisionCoordinator.init(this);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "meshUnderPointer", {
            /**
             * Gets the mesh that is currently under the pointer
             */
            get: function () {
                return this._pointerOverMesh;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "pointerX", {
            /**
             * Gets the current on-screen X position of the pointer
             */
            get: function () {
                return this._pointerX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Scene.prototype, "pointerY", {
            /**
             * Gets the current on-screen Y position of the pointer
             */
            get: function () {
                return this._pointerY;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the cached material (ie. the latest rendered one)
         * @returns the cached material
         */
        Scene.prototype.getCachedMaterial = function () {
            return this._cachedMaterial;
        };
        /**
         * Gets the cached effect (ie. the latest rendered one)
         * @returns the cached effect
         */
        Scene.prototype.getCachedEffect = function () {
            return this._cachedEffect;
        };
        /**
         * Gets the cached visibility state (ie. the latest rendered one)
         * @returns the cached visibility state
         */
        Scene.prototype.getCachedVisibility = function () {
            return this._cachedVisibility;
        };
        /**
         * Gets a boolean indicating if the current material / effect / visibility must be bind again
         * @param material defines the current material
         * @param effect defines the current effect
         * @param visibility defines the current visibility state
         * @returns true if one parameter is not cached
         */
        Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
            if (visibility === void 0) { visibility = 1; }
            return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
        };
        /**
         * Gets the engine associated with the scene
         * @returns an Engine
         */
        Scene.prototype.getEngine = function () {
            return this._engine;
        };
        /**
         * Gets the total number of vertices rendered per frame
         * @returns the total number of vertices rendered per frame
         */
        Scene.prototype.getTotalVertices = function () {
            return this._totalVertices.current;
        };
        Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
            /**
             * Gets the performance counter for total vertices
             * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
             */
            get: function () {
                return this._totalVertices;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
         * @returns the total number of active indices rendered per frame
         */
        Scene.prototype.getActiveIndices = function () {
            return this._activeIndices.current;
        };
        Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
            /**
             * Gets the performance counter for active indices
             * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
             */
            get: function () {
                return this._activeIndices;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the total number of active particles rendered per frame
         * @returns the total number of active particles rendered per frame
         */
        Scene.prototype.getActiveParticles = function () {
            return this._activeParticles.current;
        };
        Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
            /**
             * Gets the performance counter for active particles
             * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
             */
            get: function () {
                return this._activeParticles;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the total number of active bones rendered per frame
         * @returns the total number of active bones rendered per frame
         */
        Scene.prototype.getActiveBones = function () {
            return this._activeBones.current;
        };
        Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
            /**
             * Gets the performance counter for active bones
             * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
             */
            get: function () {
                return this._activeBones;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Scene.prototype.getInterFramePerfCounter = function () {
            BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Scene.prototype.getLastFrameDuration = function () {
            BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Scene.prototype.getEvaluateActiveMeshesDuration = function () {
            BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the array of active meshes
         * @returns an array of AbstractMesh
         */
        Scene.prototype.getActiveMeshes = function () {
            return this._activeMeshes;
        };
        /** @hidden */
        Scene.prototype.getRenderTargetsDuration = function () {
            BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        /** @hidden */
        Scene.prototype.getRenderDuration = function () {
            BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Scene.prototype.getParticlesDuration = function () {
            BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Scene.prototype.getSpritesDuration = function () {
            BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
            return 0;
        };
        Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
            /** @hidden */
            get: function () {
                BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
         * @returns a number
         */
        Scene.prototype.getAnimationRatio = function () {
            return this._animationRatio !== undefined ? this._animationRatio : 1;
        };
        /**
         * Gets an unique Id for the current render phase
         * @returns a number
         */
        Scene.prototype.getRenderId = function () {
            return this._renderId;
        };
        /**
         * Gets an unique Id for the current frame
         * @returns a number
         */
        Scene.prototype.getFrameId = function () {
            return this._frameId;
        };
        /** Call this function if you want to manually increment the render Id*/
        Scene.prototype.incrementRenderId = function () {
            this._renderId++;
        };
        Scene.prototype._updatePointerPosition = function (evt) {
            var canvasRect = this._engine.getRenderingCanvasClientRect();
            if (!canvasRect) {
                return;
            }
            this._pointerX = evt.clientX - canvasRect.left;
            this._pointerY = evt.clientY - canvasRect.top;
            this._unTranslatedPointerX = this._pointerX;
            this._unTranslatedPointerY = this._pointerY;
        };
        Scene.prototype._createUbo = function () {
            this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
            this._sceneUbo.addUniform("viewProjection", 16);
            this._sceneUbo.addUniform("view", 16);
        };
        Scene.prototype._createAlternateUbo = function () {
            this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
            this._alternateSceneUbo.addUniform("viewProjection", 16);
            this._alternateSceneUbo.addUniform("view", 16);
        };
        // Pointers handling
        Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
            if (pointerInfo.pickInfo) {
                if (!pointerInfo.pickInfo.ray) {
                    pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
                }
            }
        };
        /**
         * Use this method to simulate a pointer move on a mesh
         * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
         * @param pickResult pickingInfo of the object wished to simulate pointer event on
         * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
         * @returns the current scene
         */
        Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
            var evt = new PointerEvent("pointermove", pointerEventInit);
            if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
                return this;
            }
            return this._processPointerMove(pickResult, evt);
        };
        Scene.prototype._processPointerMove = function (pickResult, evt) {
            var canvas = this._engine.getRenderingCanvas();
            if (!canvas) {
                return this;
            }
            // Restore pointer
            canvas.style.cursor = this.defaultCursor;
            var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
            if (isMeshPicked) {
                this.setPointerOverMesh(pickResult.pickedMesh);
                if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
                    if (this._pointerOverMesh.actionManager.hoverCursor) {
                        canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
                    }
                    else {
                        canvas.style.cursor = this.hoverCursor;
                    }
                }
            }
            else {
                this.setPointerOverMesh(null);
            }
            for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
                var step = _a[_i];
                pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
            }
            if (pickResult) {
                var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
                if (this.onPointerMove) {
                    this.onPointerMove(evt, pickResult, type);
                }
                if (this.onPointerObservable.hasObservers()) {
                    var pi = new BABYLON.PointerInfo(type, evt, pickResult);
                    this._setRayOnPointerInfo(pi);
                    this.onPointerObservable.notifyObservers(pi, type);
                }
            }
            return this;
        };
        Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
            var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
            if (pickResult) {
                pi.ray = pickResult.ray;
            }
            this.onPrePointerObservable.notifyObservers(pi, type);
            if (pi.skipOnPointerObservable) {
                return true;
            }
            else {
                return false;
            }
        };
        /**
         * Use this method to simulate a pointer down on a mesh
         * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
         * @param pickResult pickingInfo of the object wished to simulate pointer event on
         * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
         * @returns the current scene
         */
        Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
            var evt = new PointerEvent("pointerdown", pointerEventInit);
            if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
                return this;
            }
            return this._processPointerDown(pickResult, evt);
        };
        Scene.prototype._processPointerDown = function (pickResult, evt) {
            var _this = this;
            if (pickResult && pickResult.hit && pickResult.pickedMesh) {
                this._pickedDownMesh = pickResult.pickedMesh;
                var actionManager = pickResult.pickedMesh.actionManager;
                if (actionManager) {
                    if (actionManager.hasPickTriggers) {
                        actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                        switch (evt.button) {
                            case 0:
                                actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                break;
                            case 1:
                                actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                break;
                            case 2:
                                actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                break;
                        }
                    }
                    if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
                        window.setTimeout(function () {
                            var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, _this.cameraToUseForPointers);
                            if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
                                if (_this._totalPointersPressed !== 0 &&
                                    ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
                                    !_this._isPointerSwiping()) {
                                    _this._startingPointerTime = 0;
                                    actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                                }
                            }
                        }, Scene.LongPressDelay);
                    }
                }
            }
            else {
                for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
                    var step = _a[_i];
                    pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
                }
            }
            if (pickResult) {
                var type = BABYLON.PointerEventTypes.POINTERDOWN;
                if (this.onPointerDown) {
                    this.onPointerDown(evt, pickResult, type);
                }
                if (this.onPointerObservable.hasObservers()) {
                    var pi = new BABYLON.PointerInfo(type, evt, pickResult);
                    this._setRayOnPointerInfo(pi);
                    this.onPointerObservable.notifyObservers(pi, type);
                }
            }
            return this;
        };
        /**
         * Use this method to simulate a pointer up on a mesh
         * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
         * @param pickResult pickingInfo of the object wished to simulate pointer event on
         * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
         * @returns the current scene
         */
        Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
            var evt = new PointerEvent("pointerup", pointerEventInit);
            var clickInfo = new ClickInfo();
            clickInfo.singleClick = true;
            clickInfo.ignore = true;
            if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
                return this;
            }
            return this._processPointerUp(pickResult, evt, clickInfo);
        };
        Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
            if (pickResult && pickResult && pickResult.pickedMesh) {
                this._pickedUpMesh = pickResult.pickedMesh;
                if (this._pickedDownMesh === this._pickedUpMesh) {
                    if (this.onPointerPick) {
                        this.onPointerPick(evt, pickResult);
                    }
                    if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
                        var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
                        var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
                        this._setRayOnPointerInfo(pi);
                        this.onPointerObservable.notifyObservers(pi, type_1);
                    }
                }
                if (pickResult.pickedMesh.actionManager) {
                    if (clickInfo.ignore) {
                        pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                    }
                    if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
                        pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                    }
                    if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
                        pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
                    }
                }
            }
            else {
                if (!clickInfo.ignore) {
                    for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
                        var step = _a[_i];
                        pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
                    }
                }
            }
            if (this._pickedDownMesh &&
                this._pickedDownMesh.actionManager &&
                this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
                this._pickedDownMesh !== this._pickedUpMesh) {
                this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
            }
            var type = BABYLON.PointerEventTypes.POINTERUP;
            if (this.onPointerObservable.hasObservers()) {
                if (!clickInfo.ignore) {
                    if (!clickInfo.hasSwiped) {
                        if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
                            var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
                            var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
                            this._setRayOnPointerInfo(pi);
                            this.onPointerObservable.notifyObservers(pi, type_2);
                        }
                        if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
                            var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
                            var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
                            this._setRayOnPointerInfo(pi);
                            this.onPointerObservable.notifyObservers(pi, type_3);
                        }
                    }
                }
                else {
                    var pi = new BABYLON.PointerInfo(type, evt, pickResult);
                    this._setRayOnPointerInfo(pi);
                    this.onPointerObservable.notifyObservers(pi, type);
                }
            }
            if (this.onPointerUp) {
                this.onPointerUp(evt, pickResult, type);
            }
            return this;
        };
        /**
         * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
         * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
         * @returns true if the pointer was captured
         */
        Scene.prototype.isPointerCaptured = function (pointerId) {
            if (pointerId === void 0) { pointerId = 0; }
            return this._pointerCaptures[pointerId];
        };
        /** @hidden */
        Scene.prototype._isPointerSwiping = function () {
            return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
                Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
        };
        /**
        * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
        * @param attachUp defines if you want to attach events to pointerup
        * @param attachDown defines if you want to attach events to pointerdown
        * @param attachMove defines if you want to attach events to pointermove
        */
        Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
            var _this = this;
            if (attachUp === void 0) { attachUp = true; }
            if (attachDown === void 0) { attachDown = true; }
            if (attachMove === void 0) { attachMove = true; }
            this._initActionManager = function (act, clickInfo) {
                if (!_this._meshPickProceed) {
                    var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
                    _this._currentPickResult = pickResult;
                    if (pickResult) {
                        act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
                    }
                    _this._meshPickProceed = true;
                }
                return act;
            };
            this._delayedSimpleClick = function (btn, clickInfo, cb) {
                // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
                if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
                    btn !== _this._previousButtonPressed) {
                    _this._doubleClickOccured = false;
                    clickInfo.singleClick = true;
                    clickInfo.ignore = false;
                    cb(clickInfo, _this._currentPickResult);
                }
            };
            this._initClickEvent = function (obs1, obs2, evt, cb) {
                var clickInfo = new ClickInfo();
                _this._currentPickResult = null;
                var act = null;
                var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
                    || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
                    || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
                if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
                    act = _this._initActionManager(act, clickInfo);
                    if (act) {
                        checkPicking = act.hasPickTriggers;
                    }
                }
                if (checkPicking) {
                    var btn = evt.button;
                    clickInfo.hasSwiped = _this._isPointerSwiping();
                    if (!clickInfo.hasSwiped) {
                        var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
                        if (!checkSingleClickImmediately) {
                            checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
                                !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
                            if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
                                act = _this._initActionManager(act, clickInfo);
                                if (act) {
                                    checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
                                }
                            }
                        }
                        if (checkSingleClickImmediately) {
                            // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
                            if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
                                btn !== _this._previousButtonPressed) {
                                clickInfo.singleClick = true;
                                cb(clickInfo, _this._currentPickResult);
                            }
                        }
                        // at least one double click is required to be check and exclusive double click is enabled
                        else {
                            // wait that no double click has been raised during the double click delay
                            _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
                            _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
                        }
                        var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
                            obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
                        if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
                            act = _this._initActionManager(act, clickInfo);
                            if (act) {
                                checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
                            }
                        }
                        if (checkDoubleClick) {
                            // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
                            if (btn === _this._previousButtonPressed &&
                                Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
                                !_this._doubleClickOccured) {
                                // pointer has not moved for 2 clicks, it's a double click
                                if (!clickInfo.hasSwiped &&
                                    !_this._isPointerSwiping()) {
                                    _this._previousStartingPointerTime = 0;
                                    _this._doubleClickOccured = true;
                                    clickInfo.doubleClick = true;
                                    clickInfo.ignore = false;
                                    if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
                                        clearTimeout(_this._previousDelayedSimpleClickTimeout);
                                    }
                                    _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
                                    cb(clickInfo, _this._currentPickResult);
                                }
                                // if the two successive clicks are too far, it's just two simple clicks
                                else {
                                    _this._doubleClickOccured = false;
                                    _this._previousStartingPointerTime = _this._startingPointerTime;
                                    _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
                                    _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
                                    _this._previousButtonPressed = btn;
                                    if (Scene.ExclusiveDoubleClickMode) {
                                        if (_this._previousDelayedSimpleClickTimeout) {
                                            clearTimeout(_this._previousDelayedSimpleClickTimeout);
                                        }
                                        _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
                                        cb(clickInfo, _this._previousPickResult);
                                    }
                                    else {
                                        cb(clickInfo, _this._currentPickResult);
                                    }
                                }
                            }
                            // just the first click of the double has been raised
                            else {
                                _this._doubleClickOccured = false;
                                _this._previousStartingPointerTime = _this._startingPointerTime;
                                _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
                                _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
                                _this._previousButtonPressed = btn;
                            }
                        }
                    }
                }
                clickInfo.ignore = true;
                cb(clickInfo, _this._currentPickResult);
            };
            this._onPointerMove = function (evt) {
                _this._updatePointerPosition(evt);
                // PreObservable support
                if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
                    return;
                }
                if (!_this.cameraToUseForPointers && !_this.activeCamera) {
                    return;
                }
                if (!_this.pointerMovePredicate) {
                    _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
                }
                // Meshes
                var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
                _this._processPointerMove(pickResult, evt);
            };
            this._onPointerDown = function (evt) {
                _this._totalPointersPressed++;
                _this._pickedDownMesh = null;
                _this._meshPickProceed = false;
                _this._updatePointerPosition(evt);
                if (_this.preventDefaultOnPointerDown && canvas) {
                    evt.preventDefault();
                    canvas.focus();
                }
                // PreObservable support
                if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
                    return;
                }
                if (!_this.cameraToUseForPointers && !_this.activeCamera) {
                    return;
                }
                _this._pointerCaptures[evt.pointerId] = true;
                _this._startingPointerPosition.x = _this._pointerX;
                _this._startingPointerPosition.y = _this._pointerY;
                _this._startingPointerTime = Date.now();
                if (!_this.pointerDownPredicate) {
                    _this.pointerDownPredicate = function (mesh) {
                        return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
                    };
                }
                // Meshes
                _this._pickedDownMesh = null;
                var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
                _this._processPointerDown(pickResult, evt);
            };
            this._onPointerUp = function (evt) {
                if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
                    return; // So we need to test it the pointer down was pressed before.
                }
                _this._totalPointersPressed--;
                _this._pickedUpMesh = null;
                _this._meshPickProceed = false;
                _this._updatePointerPosition(evt);
                _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
                    // PreObservable support
                    if (_this.onPrePointerObservable.hasObservers()) {
                        if (!clickInfo.ignore) {
                            if (!clickInfo.hasSwiped) {
                                if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
                                    if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
                                        return;
                                    }
                                }
                                if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
                                    if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
                                        return;
                                    }
                                }
                            }
                        }
                        else {
                            if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
                                return;
                            }
                        }
                    }
                    if (!_this.cameraToUseForPointers && !_this.activeCamera) {
                        return;
                    }
                    _this._pointerCaptures[evt.pointerId] = false;
                    if (!_this.pointerUpPredicate) {
                        _this.pointerUpPredicate = function (mesh) {
                            return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
                        };
                    }
                    // Meshes
                    if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
                        _this._initActionManager(null, clickInfo);
                    }
                    if (!pickResult) {
                        pickResult = _this._currentPickResult;
                    }
                    _this._processPointerUp(pickResult, evt, clickInfo);
                    _this._previousPickResult = _this._currentPickResult;
                });
            };
            this._onKeyDown = function (evt) {
                var type = BABYLON.KeyboardEventTypes.KEYDOWN;
                if (_this.onPreKeyboardObservable.hasObservers()) {
                    var pi = new BABYLON.KeyboardInfoPre(type, evt);
                    _this.onPreKeyboardObservable.notifyObservers(pi, type);
                    if (pi.skipOnPointerObservable) {
                        return;
                    }
                }
                if (_this.onKeyboardObservable.hasObservers()) {
                    var pi = new BABYLON.KeyboardInfo(type, evt);
                    _this.onKeyboardObservable.notifyObservers(pi, type);
                }
                if (_this.actionManager) {
                    _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
                }
            };
            this._onKeyUp = function (evt) {
                var type = BABYLON.KeyboardEventTypes.KEYUP;
                if (_this.onPreKeyboardObservable.hasObservers()) {
                    var pi = new BABYLON.KeyboardInfoPre(type, evt);
                    _this.onPreKeyboardObservable.notifyObservers(pi, type);
                    if (pi.skipOnPointerObservable) {
                        return;
                    }
                }
                if (_this.onKeyboardObservable.hasObservers()) {
                    var pi = new BABYLON.KeyboardInfo(type, evt);
                    _this.onKeyboardObservable.notifyObservers(pi, type);
                }
                if (_this.actionManager) {
                    _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
                }
            };
            var engine = this.getEngine();
            this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
                if (!canvas) {
                    return;
                }
                canvas.addEventListener("keydown", _this._onKeyDown, false);
                canvas.addEventListener("keyup", _this._onKeyUp, false);
            });
            this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
                if (!canvas) {
                    return;
                }
                canvas.removeEventListener("keydown", _this._onKeyDown);
                canvas.removeEventListener("keyup", _this._onKeyUp);
            });
            var eventPrefix = BABYLON.Tools.GetPointerPrefix();
            var canvas = this._engine.getRenderingCanvas();
            if (!canvas) {
                return;
            }
            if (attachMove) {
                canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
                // Wheel
                canvas.addEventListener('mousewheel', this._onPointerMove, false);
                canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
            }
            if (attachDown) {
                canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
            }
            if (attachUp) {
                window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
            }
            canvas.tabIndex = 1;
        };
        /** Detaches all event handlers*/
        Scene.prototype.detachControl = function () {
            var engine = this.getEngine();
            var eventPrefix = BABYLON.Tools.GetPointerPrefix();
            var canvas = engine.getRenderingCanvas();
            if (!canvas) {
                return;
            }
            canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
            canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
            window.removeEventListener(eventPrefix + "up", this._onPointerUp);
            if (this._onCanvasBlurObserver) {
                engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
            }
            if (this._onCanvasFocusObserver) {
                engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
            }
            // Wheel
            canvas.removeEventListener('mousewheel', this._onPointerMove);
            canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
            // Keyboard
            canvas.removeEventListener("keydown", this._onKeyDown);
            canvas.removeEventListener("keyup", this._onKeyUp);
            // Observables
            this.onKeyboardObservable.clear();
            this.onPreKeyboardObservable.clear();
            this.onPointerObservable.clear();
            this.onPrePointerObservable.clear();
        };
        /**
         * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
         * Delay loaded resources are not taking in account
         * @return true if all required resources are ready
         */
        Scene.prototype.isReady = function () {
            if (this._isDisposed) {
                return false;
            }
            if (this._pendingData.length > 0) {
                return false;
            }
            var index;
            var engine = this.getEngine();
            // Geometries
            for (index = 0; index < this.geometries.length; index++) {
                var geometry = this.geometries[index];
                if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                    return false;
                }
            }
            // Meshes
            for (index = 0; index < this.meshes.length; index++) {
                var mesh = this.meshes[index];
                if (!mesh.isEnabled()) {
                    continue;
                }
                if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
                    continue;
                }
                if (!mesh.isReady(true)) {
                    return false;
                }
                var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
                // Is Ready For Mesh
                for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
                    var step = _a[_i];
                    if (!step.action(mesh, hardwareInstancedRendering)) {
                        return false;
                    }
                }
            }
            // Post-processes
            if (this.activeCameras && this.activeCameras.length > 0) {
                for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
                    var camera = _c[_b];
                    if (!camera.isReady(true)) {
                        return false;
                    }
                }
            }
            else if (this.activeCamera) {
                if (!this.activeCamera.isReady(true)) {
                    return false;
                }
            }
            // Particles
            for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
                var particleSystem = _e[_d];
                if (!particleSystem.isReady()) {
                    return false;
                }
            }
            return true;
        };
        /** Resets all cached information relative to material (including effect and visibility) */
        Scene.prototype.resetCachedMaterial = function () {
            this._cachedMaterial = null;
            this._cachedEffect = null;
            this._cachedVisibility = null;
        };
        /**
         * Registers a function to be called before every frame render
         * @param func defines the function to register
         */
        Scene.prototype.registerBeforeRender = function (func) {
            this.onBeforeRenderObservable.add(func);
        };
        /**
         * Unregisters a function called before every frame render
         * @param func defines the function to unregister
         */
        Scene.prototype.unregisterBeforeRender = function (func) {
            this.onBeforeRenderObservable.removeCallback(func);
        };
        /**
         * Registers a function to be called after every frame render
         * @param func defines the function to register
         */
        Scene.prototype.registerAfterRender = function (func) {
            this.onAfterRenderObservable.add(func);
        };
        /**
         * Unregisters a function called after every frame render
         * @param func defines the function to unregister
         */
        Scene.prototype.unregisterAfterRender = function (func) {
            this.onAfterRenderObservable.removeCallback(func);
        };
        Scene.prototype._executeOnceBeforeRender = function (func) {
            var _this = this;
            var execFunc = function () {
                func();
                setTimeout(function () {
                    _this.unregisterBeforeRender(execFunc);
                });
            };
            this.registerBeforeRender(execFunc);
        };
        /**
         * The provided function will run before render once and will be disposed afterwards.
         * A timeout delay can be provided so that the function will be executed in N ms.
         * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
         * @param func The function to be executed.
         * @param timeout optional delay in ms
         */
        Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
            var _this = this;
            if (timeout !== undefined) {
                setTimeout(function () {
                    _this._executeOnceBeforeRender(func);
                }, timeout);
            }
            else {
                this._executeOnceBeforeRender(func);
            }
        };
        /** @hidden */
        Scene.prototype._addPendingData = function (data) {
            this._pendingData.push(data);
        };
        /** @hidden */
        Scene.prototype._removePendingData = function (data) {
            var wasLoading = this.isLoading;
            var index = this._pendingData.indexOf(data);
            if (index !== -1) {
                this._pendingData.splice(index, 1);
            }
            if (wasLoading && !this.isLoading) {
                this.onDataLoadedObservable.notifyObservers(this);
            }
        };
        /**
         * Returns the number of items waiting to be loaded
         * @returns the number of items waiting to be loaded
         */
        Scene.prototype.getWaitingItemsCount = function () {
            return this._pendingData.length;
        };
        Object.defineProperty(Scene.prototype, "isLoading", {
            /**
             * Returns a boolean indicating if the scene is still loading data
             */
            get: function () {
                return this._pendingData.length > 0;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Registers a function to be executed when the scene is ready
         * @param {Function} func - the function to be executed
         */
        Scene.prototype.executeWhenReady = function (func) {
            var _this = this;
            this.onReadyObservable.add(func);
            if (this._executeWhenReadyTimeoutId !== -1) {
                return;
            }
            this._executeWhenReadyTimeoutId = setTimeout(function () {
                _this._checkIsReady();
            }, 150);
        };
        /**
         * Returns a promise that resolves when the scene is ready
         * @returns A promise that resolves when the scene is ready
         */
        Scene.prototype.whenReadyAsync = function () {
            var _this = this;
            return new Promise(function (resolve) {
                _this.executeWhenReady(function () {
                    resolve();
                });
            });
        };
        /** @hidden */
        Scene.prototype._checkIsReady = function () {
            var _this = this;
            this._registerTransientComponents();
            if (this.isReady()) {
                this.onReadyObservable.notifyObservers(this);
                this.onReadyObservable.clear();
                this._executeWhenReadyTimeoutId = -1;
                return;
            }
            this._executeWhenReadyTimeoutId = setTimeout(function () {
                _this._checkIsReady();
            }, 150);
        };
        // Animations
        /**
         * Will start the animation sequence of a given target
         * @param target defines the target
         * @param from defines from which frame should animation start
         * @param to defines until which frame should animation run.
         * @param weight defines the weight to apply to the animation (1.0 by default)
         * @param loop defines if the animation loops
         * @param speedRatio defines the speed in which to run the animation (1.0 by default)
         * @param onAnimationEnd defines the function to be executed when the animation ends
         * @param animatable defines an animatable object. If not provided a new one will be created from the given params
         * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
         * @returns the animatable object created for this animation
         */
        Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
            if (weight === void 0) { weight = 1.0; }
            if (speedRatio === void 0) { speedRatio = 1.0; }
            var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
            returnedAnimatable.weight = weight;
            return returnedAnimatable;
        };
        /**
         * Will start the animation sequence of a given target
         * @param target defines the target
         * @param from defines from which frame should animation start
         * @param to defines until which frame should animation run.
         * @param loop defines if the animation loops
         * @param speedRatio defines the speed in which to run the animation (1.0 by default)
         * @param onAnimationEnd defines the function to be executed when the animation ends
         * @param animatable defines an animatable object. If not provided a new one will be created from the given params
         * @param stopCurrent defines if the current animations must be stopped first (true by default)
         * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
         * @returns the animatable object created for this animation
         */
        Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
            if (speedRatio === void 0) { speedRatio = 1.0; }
            if (stopCurrent === void 0) { stopCurrent = true; }
            if (from > to && speedRatio > 0) {
                speedRatio *= -1;
            }
            if (stopCurrent) {
                this.stopAnimation(target, undefined, targetMask);
            }
            if (!animatable) {
                animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
            }
            var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
            // Local animations
            if (target.animations && shouldRunTargetAnimations) {
                animatable.appendAnimations(target, target.animations);
            }
            // Children animations
            if (target.getAnimatables) {
                var animatables = target.getAnimatables();
                for (var index = 0; index < animatables.length; index++) {
                    this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
                }
            }
            animatable.reset();
            return animatable;
        };
        /**
         * Begin a new animation on a given node
         * @param target defines the target where the animation will take place
         * @param animations defines the list of animations to start
         * @param from defines the initial value
         * @param to defines the final value
         * @param loop defines if you want animation to loop (off by default)
         * @param speedRatio defines the speed ratio to apply to all animations
         * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
         * @returns the list of created animatables
         */
        Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
            if (speedRatio === undefined) {
                speedRatio = 1.0;
            }
            var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
            return animatable;
        };
        /**
         * Begin a new animation on a given node and its hierarchy
         * @param target defines the root node where the animation will take place
         * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
         * @param animations defines the list of animations to start
         * @param from defines the initial value
         * @param to defines the final value
         * @param loop defines if you want animation to loop (off by default)
         * @param speedRatio defines the speed ratio to apply to all animations
         * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
         * @returns the list of animatables created for all nodes
         */
        Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
            var children = target.getDescendants(directDescendantsOnly);
            var result = [];
            result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
            for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
                var child = children_1[_i];
                result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
            }
            return result;
        };
        /**
         * Gets the animatable associated with a specific target
         * @param target defines the target of the animatable
         * @returns the required animatable if found
         */
        Scene.prototype.getAnimatableByTarget = function (target) {
            for (var index = 0; index < this._activeAnimatables.length; index++) {
                if (this._activeAnimatables[index].target === target) {
                    return this._activeAnimatables[index];
                }
            }
            return null;
        };
        /**
         * Gets all animatables associated with a given target
         * @param target defines the target to look animatables for
         * @returns an array of Animatables
         */
        Scene.prototype.getAllAnimatablesByTarget = function (target) {
            var result = [];
            for (var index = 0; index < this._activeAnimatables.length; index++) {
                if (this._activeAnimatables[index].target === target) {
                    result.push(this._activeAnimatables[index]);
                }
            }
            return result;
        };
        Object.defineProperty(Scene.prototype, "animatables", {
            /**
             * Gets all animatable attached to the scene
             */
            get: function () {
                return this._activeAnimatables;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Will stop the animation of the given target
         * @param target - the target
         * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
         * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
         */
        Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
            var animatables = this.getAllAnimatablesByTarget(target);
            for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
                var animatable = animatables_1[_i];
                animatable.stop(animationName, targetMask);
            }
        };
        /**
         * Stops and removes all animations that have been applied to the scene
         */
        Scene.prototype.stopAllAnimations = function () {
            if (this._activeAnimatables) {
                for (var i = 0; i < this._activeAnimatables.length; i++) {
                    this._activeAnimatables[i].stop();
                }
                this._activeAnimatables = [];
            }
            for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
                var group = _a[_i];
                group.stop();
            }
        };
        Scene.prototype._animate = function () {
            if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
                return;
            }
            // Getting time
            var now = BABYLON.Tools.Now;
            if (!this._animationTimeLast) {
                if (this._pendingData.length > 0) {
                    return;
                }
                this._animationTimeLast = now;
            }
            var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
            this._animationTime += deltaTime;
            this._animationTimeLast = now;
            for (var index = 0; index < this._activeAnimatables.length; index++) {
                this._activeAnimatables[index]._animate(this._animationTime);
            }
            // Late animation bindings
            this._processLateAnimationBindings();
        };
        /** @hidden */
        Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
            var target = runtimeAnimation.target;
            this._registeredForLateAnimationBindings.pushNoDuplicate(target);
            if (!target._lateAnimationHolders) {
                target._lateAnimationHolders = {};
            }
            if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
                target._lateAnimationHolders[runtimeAnimation.targetPath] = {
                    totalWeight: 0,
                    animations: [],
                    originalValue: originalValue
                };
            }
            target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
            target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
        };
        Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
            var normalizer = 1.0;
            var finalPosition = BABYLON.Tmp.Vector3[0];
            var finalScaling = BABYLON.Tmp.Vector3[1];
            var finalQuaternion = BABYLON.Tmp.Quaternion[0];
            var startIndex = 0;
            var originalAnimation = holder.animations[0];
            var originalValue = holder.originalValue;
            var scale = 1;
            if (holder.totalWeight < 1.0) {
                // We need to mix the original value in
                originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
                scale = 1.0 - holder.totalWeight;
            }
            else {
                startIndex = 1;
                // We need to normalize the weights
                normalizer = holder.totalWeight;
                originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
                scale = originalAnimation.weight / normalizer;
                if (scale == 1) {
                    return originalAnimation.currentValue;
                }
            }
            finalScaling.scaleInPlace(scale);
            finalPosition.scaleInPlace(scale);
            finalQuaternion.scaleInPlace(scale);
            for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
                var runtimeAnimation = holder.animations[animIndex];
                var scale = runtimeAnimation.weight / normalizer;
                var currentPosition = BABYLON.Tmp.Vector3[2];
                var currentScaling = BABYLON.Tmp.Vector3[3];
                var currentQuaternion = BABYLON.Tmp.Quaternion[1];
                runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
                currentScaling.scaleAndAddToRef(scale, finalScaling);
                currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
                currentPosition.scaleAndAddToRef(scale, finalPosition);
            }
            BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
            return originalAnimation._workValue;
        };
        Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
            var originalAnimation = holder.animations[0];
            var originalValue = holder.originalValue;
            if (holder.animations.length === 1) {
                BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
                return refQuaternion;
            }
            var normalizer = 1.0;
            var quaternions;
            var weights;
            if (holder.totalWeight < 1.0) {
                var scale = 1.0 - holder.totalWeight;
                quaternions = [];
                weights = [];
                quaternions.push(originalValue);
                weights.push(scale);
            }
            else {
                if (holder.animations.length === 2) { // Slerp as soon as we can
                    BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
                    return refQuaternion;
                }
                quaternions = [];
                weights = [];
                normalizer = holder.totalWeight;
            }
            for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
                var runtimeAnimation = holder.animations[animIndex];
                quaternions.push(runtimeAnimation.currentValue);
                weights.push(runtimeAnimation.weight / normalizer);
            }
            // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
            var cumulativeAmount = 0;
            var cumulativeQuaternion = null;
            for (var index = 0; index < quaternions.length;) {
                if (!cumulativeQuaternion) {
                    BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
                    cumulativeQuaternion = refQuaternion;
                    cumulativeAmount = weights[index] + weights[index + 1];
                    index += 2;
                    continue;
                }
                cumulativeAmount += weights[index];
                BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
                index++;
            }
            return cumulativeQuaternion;
        };
        Scene.prototype._processLateAnimationBindings = function () {
            if (!this._registeredForLateAnimationBindings.length) {
                return;
            }
            for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
                var target = this._registeredForLateAnimationBindings.data[index];
                for (var path in target._lateAnimationHolders) {
                    var holder = target._lateAnimationHolders[path];
                    var originalAnimation = holder.animations[0];
                    var originalValue = holder.originalValue;
                    var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
                    var finalValue = target[path];
                    if (matrixDecomposeMode) {
                        finalValue = this._processLateAnimationBindingsForMatrices(holder);
                    }
                    else {
                        var quaternionMode = originalValue.w !== undefined;
                        if (quaternionMode) {
                            finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
                        }
                        else {
                            var startIndex = 0;
                            var normalizer = 1.0;
                            if (holder.totalWeight < 1.0) {
                                // We need to mix the original value in
                                if (originalValue.scale) {
                                    finalValue = originalValue.scale(1.0 - holder.totalWeight);
                                }
                                else {
                                    finalValue = originalValue * (1.0 - holder.totalWeight);
                                }
                            }
                            else {
                                // We need to normalize the weights
                                normalizer = holder.totalWeight;
                                var scale_1 = originalAnimation.weight / normalizer;
                                if (scale_1 !== 1) {
                                    if (originalAnimation.currentValue.scale) {
                                        finalValue = originalAnimation.currentValue.scale(scale_1);
                                    }
                                    else {
                                        finalValue = originalAnimation.currentValue * scale_1;
                                    }
                                }
                                else {
                                    finalValue = originalAnimation.currentValue;
                                }
                                startIndex = 1;
                            }
                            for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
                                var runtimeAnimation = holder.animations[animIndex];
                                var scale = runtimeAnimation.weight / normalizer;
                                if (runtimeAnimation.currentValue.scaleAndAddToRef) {
                                    runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
                                }
                                else {
                                    finalValue += runtimeAnimation.currentValue * scale;
                                }
                            }
                        }
                    }
                    target[path] = finalValue;
                }
                target._lateAnimationHolders = {};
            }
            this._registeredForLateAnimationBindings.reset();
        };
        // Matrix
        /** @hidden */
        Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
            this._useAlternateCameraConfiguration = active;
        };
        /**
         * Gets the current view matrix
         * @returns a Matrix
         */
        Scene.prototype.getViewMatrix = function () {
            return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
        };
        /**
         * Gets the current projection matrix
         * @returns a Matrix
         */
        Scene.prototype.getProjectionMatrix = function () {
            return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
        };
        /**
         * Gets the current transform matrix
         * @returns a Matrix made of View * Projection
         */
        Scene.prototype.getTransformMatrix = function () {
            return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
        };
        /**
         * Sets the current transform matrix
         * @param view defines the View matrix to use
         * @param projection defines the Projection matrix to use
         */
        Scene.prototype.setTransformMatrix = function (view, projection) {
            if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
                return;
            }
            this._viewUpdateFlag = view.updateFlag;
            this._projectionUpdateFlag = projection.updateFlag;
            this._viewMatrix = view;
            this._projectionMatrix = projection;
            this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
            // Update frustum
            if (!this._frustumPlanes) {
                this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
            }
            else {
                BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
            }
            if (this.activeCamera && this.activeCamera._alternateCamera) {
                var otherCamera = this.activeCamera._alternateCamera;
                otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
                BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
            }
            if (this._sceneUbo.useUbo) {
                this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
                this._sceneUbo.updateMatrix("view", this._viewMatrix);
                this._sceneUbo.update();
            }
        };
        /** @hidden */
        Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
            if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
                return;
            }
            this._alternateViewUpdateFlag = view.updateFlag;
            this._alternateProjectionUpdateFlag = projection.updateFlag;
            this._alternateViewMatrix = view;
            this._alternateProjectionMatrix = projection;
            if (!this._alternateTransformMatrix) {
                this._alternateTransformMatrix = BABYLON.Matrix.Zero();
            }
            this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
            if (!this._alternateSceneUbo) {
                this._createAlternateUbo();
            }
            if (this._alternateSceneUbo.useUbo) {
                this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
                this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
                this._alternateSceneUbo.update();
            }
        };
        /**
         * Gets the uniform buffer used to store scene data
         * @returns a UniformBuffer
         */
        Scene.prototype.getSceneUniformBuffer = function () {
            return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
        };
        /**
         * Gets an unique (relatively to the current scene) Id
         * @returns an unique number for the scene
         */
        Scene.prototype.getUniqueId = function () {
            var result = Scene._uniqueIdCounter;
            Scene._uniqueIdCounter++;
            return result;
        };
        /**
         * Add a mesh to the list of scene's meshes
         * @param newMesh defines the mesh to add
         * @param recursive if all child meshes should also be added to the scene
         */
        Scene.prototype.addMesh = function (newMesh, recursive) {
            var _this = this;
            if (recursive === void 0) { recursive = false; }
            this.meshes.push(newMesh);
            //notify the collision coordinator
            if (this.collisionCoordinator) {
                this.collisionCoordinator.onMeshAdded(newMesh);
            }
            newMesh._resyncLightSources();
            this.onNewMeshAddedObservable.notifyObservers(newMesh);
            if (recursive) {
                newMesh.getChildMeshes().forEach(function (m) {
                    _this.addMesh(m);
                });
            }
        };
        /**
         * Remove a mesh for the list of scene's meshes
         * @param toRemove defines the mesh to remove
         * @param recursive if all child meshes should also be removed from the scene
         * @returns the index where the mesh was in the mesh list
         */
        Scene.prototype.removeMesh = function (toRemove, recursive) {
            var _this = this;
            if (recursive === void 0) { recursive = false; }
            var index = this.meshes.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if mesh found
                this.meshes.splice(index, 1);
            }
            this.onMeshRemovedObservable.notifyObservers(toRemove);
            if (recursive) {
                toRemove.getChildMeshes().forEach(function (m) {
                    _this.removeMesh(m);
                });
            }
            return index;
        };
        /**
         * Add a transform node to the list of scene's transform nodes
         * @param newTransformNode defines the transform node to add
         */
        Scene.prototype.addTransformNode = function (newTransformNode) {
            this.transformNodes.push(newTransformNode);
            this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
        };
        /**
         * Remove a transform node for the list of scene's transform nodes
         * @param toRemove defines the transform node to remove
         * @returns the index where the transform node was in the transform node list
         */
        Scene.prototype.removeTransformNode = function (toRemove) {
            var index = this.transformNodes.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if found
                this.transformNodes.splice(index, 1);
            }
            this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        /**
         * Remove a skeleton for the list of scene's skeletons
         * @param toRemove defines the skeleton to remove
         * @returns the index where the skeleton was in the skeleton list
         */
        Scene.prototype.removeSkeleton = function (toRemove) {
            var index = this.skeletons.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if found
                this.skeletons.splice(index, 1);
            }
            return index;
        };
        /**
         * Remove a morph target for the list of scene's morph targets
         * @param toRemove defines the morph target to remove
         * @returns the index where the morph target was in the morph target list
         */
        Scene.prototype.removeMorphTargetManager = function (toRemove) {
            var index = this.morphTargetManagers.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if found
                this.morphTargetManagers.splice(index, 1);
            }
            return index;
        };
        /**
         * Remove a light for the list of scene's lights
         * @param toRemove defines the light to remove
         * @returns the index where the light was in the light list
         */
        Scene.prototype.removeLight = function (toRemove) {
            var index = this.lights.indexOf(toRemove);
            if (index !== -1) {
                // Remove from meshes
                for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
                    var mesh = _a[_i];
                    mesh._removeLightSource(toRemove);
                }
                // Remove from the scene if mesh found
                this.lights.splice(index, 1);
                this.sortLightsByPriority();
            }
            this.onLightRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        /**
         * Remove a camera for the list of scene's cameras
         * @param toRemove defines the camera to remove
         * @returns the index where the camera was in the camera list
         */
        Scene.prototype.removeCamera = function (toRemove) {
            var index = this.cameras.indexOf(toRemove);
            if (index !== -1) {
                // Remove from the scene if mesh found
                this.cameras.splice(index, 1);
            }
            // Remove from activeCameras
            var index2 = this.activeCameras.indexOf(toRemove);
            if (index2 !== -1) {
                // Remove from the scene if mesh found
                this.activeCameras.splice(index2, 1);
            }
            // Reset the activeCamera
            if (this.activeCamera === toRemove) {
                if (this.cameras.length > 0) {
                    this.activeCamera = this.cameras[0];
                }
                else {
                    this.activeCamera = null;
                }
            }
            this.onCameraRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        /**
         * Remove a particle system for the list of scene's particle systems
         * @param toRemove defines the particle system to remove
         * @returns the index where the particle system was in the particle system list
         */
        Scene.prototype.removeParticleSystem = function (toRemove) {
            var index = this.particleSystems.indexOf(toRemove);
            if (index !== -1) {
                this.particleSystems.splice(index, 1);
            }
            return index;
        };
        /**
         * Remove a animation for the list of scene's animations
         * @param toRemove defines the animation to remove
         * @returns the index where the animation was in the animation list
         */
        Scene.prototype.removeAnimation = function (toRemove) {
            var index = this.animations.indexOf(toRemove);
            if (index !== -1) {
                this.animations.splice(index, 1);
            }
            return index;
        };
        /**
         * Removes the given animation group from this scene.
         * @param toRemove The animation group to remove
         * @returns The index of the removed animation group
         */
        Scene.prototype.removeAnimationGroup = function (toRemove) {
            var index = this.animationGroups.indexOf(toRemove);
            if (index !== -1) {
                this.animationGroups.splice(index, 1);
            }
            return index;
        };
        /**
         * Removes the given multi-material from this scene.
         * @param toRemove The multi-material to remove
         * @returns The index of the removed multi-material
         */
        Scene.prototype.removeMultiMaterial = function (toRemove) {
            var index = this.multiMaterials.indexOf(toRemove);
            if (index !== -1) {
                this.multiMaterials.splice(index, 1);
            }
            return index;
        };
        /**
         * Removes the given material from this scene.
         * @param toRemove The material to remove
         * @returns The index of the removed material
         */
        Scene.prototype.removeMaterial = function (toRemove) {
            var index = this.materials.indexOf(toRemove);
            if (index !== -1) {
                this.materials.splice(index, 1);
            }
            this.onMaterialRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        /**
         * Removes the given action manager from this scene.
         * @param toRemove The action manager to remove
         * @returns The index of the removed action manager
         */
        Scene.prototype.removeActionManager = function (toRemove) {
            var index = this.actionManagers.indexOf(toRemove);
            if (index !== -1) {
                this.actionManagers.splice(index, 1);
            }
            return index;
        };
        /**
         * Removes the given texture from this scene.
         * @param toRemove The texture to remove
         * @returns The index of the removed texture
         */
        Scene.prototype.removeTexture = function (toRemove) {
            var index = this.textures.indexOf(toRemove);
            if (index !== -1) {
                this.textures.splice(index, 1);
            }
            this.onTextureRemovedObservable.notifyObservers(toRemove);
            return index;
        };
        /**
         * Adds the given light to this scene
         * @param newLight The light to add
         */
        Scene.prototype.addLight = function (newLight) {
            this.lights.push(newLight);
            this.sortLightsByPriority();
            // Add light to all meshes (To support if the light is removed and then readded)
            for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                if (mesh._lightSources.indexOf(newLight) === -1) {
                    mesh._lightSources.push(newLight);
                    mesh._resyncLightSources();
                }
            }
            this.onNewLightAddedObservable.notifyObservers(newLight);
        };
        /**
         * Sorts the list list based on light priorities
         */
        Scene.prototype.sortLightsByPriority = function () {
            if (this.requireLightSorting) {
                this.lights.sort(BABYLON.Light.CompareLightsPriority);
            }
        };
        /**
         * Adds the given camera to this scene
         * @param newCamera The camera to add
         */
        Scene.prototype.addCamera = function (newCamera) {
            this.cameras.push(newCamera);
            this.onNewCameraAddedObservable.notifyObservers(newCamera);
        };
        /**
         * Adds the given skeleton to this scene
         * @param newSkeleton The skeleton to add
         */
        Scene.prototype.addSkeleton = function (newSkeleton) {
            this.skeletons.push(newSkeleton);
        };
        /**
         * Adds the given particle system to this scene
         * @param newParticleSystem The particle system to add
         */
        Scene.prototype.addParticleSystem = function (newParticleSystem) {
            this.particleSystems.push(newParticleSystem);
        };
        /**
         * Adds the given animation to this scene
         * @param newAnimation The animation to add
         */
        Scene.prototype.addAnimation = function (newAnimation) {
            this.animations.push(newAnimation);
        };
        /**
         * Adds the given animation group to this scene.
         * @param newAnimationGroup The animation group to add
         */
        Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
            this.animationGroups.push(newAnimationGroup);
        };
        /**
         * Adds the given multi-material to this scene
         * @param newMultiMaterial The multi-material to add
         */
        Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
            this.multiMaterials.push(newMultiMaterial);
        };
        /**
         * Adds the given material to this scene
         * @param newMaterial The material to add
         */
        Scene.prototype.addMaterial = function (newMaterial) {
            this.materials.push(newMaterial);
            this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
        };
        /**
         * Adds the given morph target to this scene
         * @param newMorphTargetManager The morph target to add
         */
        Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
            this.morphTargetManagers.push(newMorphTargetManager);
        };
        /**
         * Adds the given geometry to this scene
         * @param newGeometry The geometry to add
         */
        Scene.prototype.addGeometry = function (newGeometry) {
            this.geometries.push(newGeometry);
        };
        /**
         * Adds the given action manager to this scene
         * @param newActionManager The action manager to add
         */
        Scene.prototype.addActionManager = function (newActionManager) {
            this.actionManagers.push(newActionManager);
        };
        /**
         * Adds the given texture to this scene.
         * @param newTexture The texture to add
         */
        Scene.prototype.addTexture = function (newTexture) {
            this.textures.push(newTexture);
            this.onNewTextureAddedObservable.notifyObservers(newTexture);
        };
        /**
         * Switch active camera
         * @param newCamera defines the new active camera
         * @param attachControl defines if attachControl must be called for the new active camera (default: true)
         */
        Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
            if (attachControl === void 0) { attachControl = true; }
            var canvas = this._engine.getRenderingCanvas();
            if (!canvas) {
                return;
            }
            if (this.activeCamera) {
                this.activeCamera.detachControl(canvas);
            }
            this.activeCamera = newCamera;
            if (attachControl) {
                newCamera.attachControl(canvas);
            }
        };
        /**
         * sets the active camera of the scene using its ID
         * @param id defines the camera's ID
         * @return the new active camera or null if none found.
         */
        Scene.prototype.setActiveCameraByID = function (id) {
            var camera = this.getCameraByID(id);
            if (camera) {
                this.activeCamera = camera;
                return camera;
            }
            return null;
        };
        /**
         * sets the active camera of the scene using its name
         * @param name defines the camera's name
         * @returns the new active camera or null if none found.
         */
        Scene.prototype.setActiveCameraByName = function (name) {
            var camera = this.getCameraByName(name);
            if (camera) {
                this.activeCamera = camera;
                return camera;
            }
            return null;
        };
        /**
         * get an animation group using its name
         * @param name defines the material's name
         * @return the animation group or null if none found.
         */
        Scene.prototype.getAnimationGroupByName = function (name) {
            for (var index = 0; index < this.animationGroups.length; index++) {
                if (this.animationGroups[index].name === name) {
                    return this.animationGroups[index];
                }
            }
            return null;
        };
        /**
         * get a material using its id
         * @param id defines the material's ID
         * @return the material or null if none found.
         */
        Scene.prototype.getMaterialByID = function (id) {
            for (var index = 0; index < this.materials.length; index++) {
                if (this.materials[index].id === id) {
                    return this.materials[index];
                }
            }
            return null;
        };
        /**
         * Gets a material using its name
         * @param name defines the material's name
         * @return the material or null if none found.
         */
        Scene.prototype.getMaterialByName = function (name) {
            for (var index = 0; index < this.materials.length; index++) {
                if (this.materials[index].name === name) {
                    return this.materials[index];
                }
            }
            return null;
        };
        /**
         * Gets a camera using its id
         * @param id defines the id to look for
         * @returns the camera or null if not found
         */
        Scene.prototype.getCameraByID = function (id) {
            for (var index = 0; index < this.cameras.length; index++) {
                if (this.cameras[index].id === id) {
                    return this.cameras[index];
                }
            }
            return null;
        };
        /**
         * Gets a camera using its unique id
         * @param uniqueId defines the unique id to look for
         * @returns the camera or null if not found
         */
        Scene.prototype.getCameraByUniqueID = function (uniqueId) {
            for (var index = 0; index < this.cameras.length; index++) {
                if (this.cameras[index].uniqueId === uniqueId) {
                    return this.cameras[index];
                }
            }
            return null;
        };
        /**
         * Gets a camera using its name
         * @param name defines the camera's name
         * @return the camera or null if none found.
         */
        Scene.prototype.getCameraByName = function (name) {
            for (var index = 0; index < this.cameras.length; index++) {
                if (this.cameras[index].name === name) {
                    return this.cameras[index];
                }
            }
            return null;
        };
        /**
         * Gets a bone using its id
         * @param id defines the bone's id
         * @return the bone or null if not found
         */
        Scene.prototype.getBoneByID = function (id) {
            for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
                var skeleton = this.skeletons[skeletonIndex];
                for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
                    if (skeleton.bones[boneIndex].id === id) {
                        return skeleton.bones[boneIndex];
                    }
                }
            }
            return null;
        };
        /**
        * Gets a bone using its id
        * @param name defines the bone's name
        * @return the bone or null if not found
        */
        Scene.prototype.getBoneByName = function (name) {
            for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
                var skeleton = this.skeletons[skeletonIndex];
                for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
                    if (skeleton.bones[boneIndex].name === name) {
                        return skeleton.bones[boneIndex];
                    }
                }
            }
            return null;
        };
        /**
         * Gets a light node using its name
         * @param name defines the the light's name
         * @return the light or null if none found.
         */
        Scene.prototype.getLightByName = function (name) {
            for (var index = 0; index < this.lights.length; index++) {
                if (this.lights[index].name === name) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * Gets a light node using its id
         * @param id defines the light's id
         * @return the light or null if none found.
         */
        Scene.prototype.getLightByID = function (id) {
            for (var index = 0; index < this.lights.length; index++) {
                if (this.lights[index].id === id) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * Gets a light node using its scene-generated unique ID
         * @param uniqueId defines the light's unique id
         * @return the light or null if none found.
         */
        Scene.prototype.getLightByUniqueID = function (uniqueId) {
            for (var index = 0; index < this.lights.length; index++) {
                if (this.lights[index].uniqueId === uniqueId) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * Gets a particle system by id
         * @param id defines the particle system id
         * @return the corresponding system or null if none found
         */
        Scene.prototype.getParticleSystemByID = function (id) {
            for (var index = 0; index < this.particleSystems.length; index++) {
                if (this.particleSystems[index].id === id) {
                    return this.particleSystems[index];
                }
            }
            return null;
        };
        /**
         * Gets a geometry using its ID
         * @param id defines the geometry's id
         * @return the geometry or null if none found.
         */
        Scene.prototype.getGeometryByID = function (id) {
            for (var index = 0; index < this.geometries.length; index++) {
                if (this.geometries[index].id === id) {
                    return this.geometries[index];
                }
            }
            return null;
        };
        /**
         * Add a new geometry to this scene
         * @param geometry defines the geometry to be added to the scene.
         * @param force defines if the geometry must be pushed even if a geometry with this id already exists
         * @return a boolean defining if the geometry was added or not
         */
        Scene.prototype.pushGeometry = function (geometry, force) {
            if (!force && this.getGeometryByID(geometry.id)) {
                return false;
            }
            this.geometries.push(geometry);
            //notify the collision coordinator
            if (this.collisionCoordinator) {
                this.collisionCoordinator.onGeometryAdded(geometry);
            }
            this.onNewGeometryAddedObservable.notifyObservers(geometry);
            return true;
        };
        /**
         * Removes an existing geometry
         * @param geometry defines the geometry to be removed from the scene
         * @return a boolean defining if the geometry was removed or not
         */
        Scene.prototype.removeGeometry = function (geometry) {
            var index = this.geometries.indexOf(geometry);
            if (index > -1) {
                this.geometries.splice(index, 1);
                //notify the collision coordinator
                if (this.collisionCoordinator) {
                    this.collisionCoordinator.onGeometryDeleted(geometry);
                }
                this.onGeometryRemovedObservable.notifyObservers(geometry);
                return true;
            }
            return false;
        };
        /**
         * Gets the list of geometries attached to the scene
         * @returns an array of Geometry
         */
        Scene.prototype.getGeometries = function () {
            return this.geometries;
        };
        /**
         * Gets the first added mesh found of a given ID
         * @param id defines the id to search for
         * @return the mesh found or null if not found at all
         */
        Scene.prototype.getMeshByID = function (id) {
            for (var index = 0; index < this.meshes.length; index++) {
                if (this.meshes[index].id === id) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        /**
         * Gets a list of meshes using their id
         * @param id defines the id to search for
         * @returns a list of meshes
         */
        Scene.prototype.getMeshesByID = function (id) {
            return this.meshes.filter(function (m) {
                return m.id === id;
            });
        };
        /**
         * Gets the first added transform node found of a given ID
         * @param id defines the id to search for
         * @return the found transform node or null if not found at all.
         */
        Scene.prototype.getTransformNodeByID = function (id) {
            for (var index = 0; index < this.transformNodes.length; index++) {
                if (this.transformNodes[index].id === id) {
                    return this.transformNodes[index];
                }
            }
            return null;
        };
        /**
         * Gets a list of transform nodes using their id
         * @param id defines the id to search for
         * @returns a list of transform nodes
         */
        Scene.prototype.getTransformNodesByID = function (id) {
            return this.transformNodes.filter(function (m) {
                return m.id === id;
            });
        };
        /**
         * Gets a mesh with its auto-generated unique id
         * @param uniqueId defines the unique id to search for
         * @return the found mesh or null if not found at all.
         */
        Scene.prototype.getMeshByUniqueID = function (uniqueId) {
            for (var index = 0; index < this.meshes.length; index++) {
                if (this.meshes[index].uniqueId === uniqueId) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        /**
         * Gets a the last added mesh using a given id
         * @param id defines the id to search for
         * @return the found mesh or null if not found at all.
         */
        Scene.prototype.getLastMeshByID = function (id) {
            for (var index = this.meshes.length - 1; index >= 0; index--) {
                if (this.meshes[index].id === id) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        /**
         * Gets a the last added node (Mesh, Camera, Light) using a given id
         * @param id defines the id to search for
         * @return the found node or null if not found at all
         */
        Scene.prototype.getLastEntryByID = function (id) {
            var index;
            for (index = this.meshes.length - 1; index >= 0; index--) {
                if (this.meshes[index].id === id) {
                    return this.meshes[index];
                }
            }
            for (index = this.transformNodes.length - 1; index >= 0; index--) {
                if (this.transformNodes[index].id === id) {
                    return this.transformNodes[index];
                }
            }
            for (index = this.cameras.length - 1; index >= 0; index--) {
                if (this.cameras[index].id === id) {
                    return this.cameras[index];
                }
            }
            for (index = this.lights.length - 1; index >= 0; index--) {
                if (this.lights[index].id === id) {
                    return this.lights[index];
                }
            }
            return null;
        };
        /**
         * Gets a node (Mesh, Camera, Light) using a given id
         * @param id defines the id to search for
         * @return the found node or null if not found at all
         */
        Scene.prototype.getNodeByID = function (id) {
            var mesh = this.getMeshByID(id);
            if (mesh) {
                return mesh;
            }
            var light = this.getLightByID(id);
            if (light) {
                return light;
            }
            var camera = this.getCameraByID(id);
            if (camera) {
                return camera;
            }
            var bone = this.getBoneByID(id);
            return bone;
        };
        /**
         * Gets a node (Mesh, Camera, Light) using a given name
         * @param name defines the name to search for
         * @return the found node or null if not found at all.
         */
        Scene.prototype.getNodeByName = function (name) {
            var mesh = this.getMeshByName(name);
            if (mesh) {
                return mesh;
            }
            var light = this.getLightByName(name);
            if (light) {
                return light;
            }
            var camera = this.getCameraByName(name);
            if (camera) {
                return camera;
            }
            var bone = this.getBoneByName(name);
            return bone;
        };
        /**
         * Gets a mesh using a given name
         * @param name defines the name to search for
         * @return the found mesh or null if not found at all.
         */
        Scene.prototype.getMeshByName = function (name) {
            for (var index = 0; index < this.meshes.length; index++) {
                if (this.meshes[index].name === name) {
                    return this.meshes[index];
                }
            }
            return null;
        };
        /**
         * Gets a transform node using a given name
         * @param name defines the name to search for
         * @return the found transform node or null if not found at all.
         */
        Scene.prototype.getTransformNodeByName = function (name) {
            for (var index = 0; index < this.transformNodes.length; index++) {
                if (this.transformNodes[index].name === name) {
                    return this.transformNodes[index];
                }
            }
            return null;
        };
        /**
         * Gets a skeleton using a given id (if many are found, this function will pick the last one)
         * @param id defines the id to search for
         * @return the found skeleton or null if not found at all.
         */
        Scene.prototype.getLastSkeletonByID = function (id) {
            for (var index = this.skeletons.length - 1; index >= 0; index--) {
                if (this.skeletons[index].id === id) {
                    return this.skeletons[index];
                }
            }
            return null;
        };
        /**
         * Gets a skeleton using a given id (if many are found, this function will pick the first one)
         * @param id defines the id to search for
         * @return the found skeleton or null if not found at all.
         */
        Scene.prototype.getSkeletonById = function (id) {
            for (var index = 0; index < this.skeletons.length; index++) {
                if (this.skeletons[index].id === id) {
                    return this.skeletons[index];
                }
            }
            return null;
        };
        /**
         * Gets a skeleton using a given name
         * @param name defines the name to search for
         * @return the found skeleton or null if not found at all.
         */
        Scene.prototype.getSkeletonByName = function (name) {
            for (var index = 0; index < this.skeletons.length; index++) {
                if (this.skeletons[index].name === name) {
                    return this.skeletons[index];
                }
            }
            return null;
        };
        /**
         * Gets a morph target manager  using a given id (if many are found, this function will pick the last one)
         * @param id defines the id to search for
         * @return the found morph target manager or null if not found at all.
         */
        Scene.prototype.getMorphTargetManagerById = function (id) {
            for (var index = 0; index < this.morphTargetManagers.length; index++) {
                if (this.morphTargetManagers[index].uniqueId === id) {
                    return this.morphTargetManagers[index];
                }
            }
            return null;
        };
        /**
         * Gets a boolean indicating if the given mesh is active
         * @param mesh defines the mesh to look for
         * @returns true if the mesh is in the active list
         */
        Scene.prototype.isActiveMesh = function (mesh) {
            return (this._activeMeshes.indexOf(mesh) !== -1);
        };
        Object.defineProperty(Scene.prototype, "uid", {
            /**
             * Return a unique id as a string which can serve as an identifier for the scene
             */
            get: function () {
                if (!this._uid) {
                    this._uid = BABYLON.Tools.RandomId();
                }
                return this._uid;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Add an externaly attached data from its key.
         * This method call will fail and return false, if such key already exists.
         * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
         * @param key the unique key that identifies the data
         * @param data the data object to associate to the key for this Engine instance
         * @return true if no such key were already present and the data was added successfully, false otherwise
         */
        Scene.prototype.addExternalData = function (key, data) {
            if (!this._externalData) {
                this._externalData = new BABYLON.StringDictionary();
            }
            return this._externalData.add(key, data);
        };
        /**
         * Get an externaly attached data from its key
         * @param key the unique key that identifies the data
         * @return the associated data, if present (can be null), or undefined if not present
         */
        Scene.prototype.getExternalData = function (key) {
            if (!this._externalData) {
                return null;
            }
            return this._externalData.get(key);
        };
        /**
         * Get an externaly attached data from its key, create it using a factory if it's not already present
         * @param key the unique key that identifies the data
         * @param factory the factory that will be called to create the instance if and only if it doesn't exists
         * @return the associated data, can be null if the factory returned null.
         */
        Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
            if (!this._externalData) {
                this._externalData = new BABYLON.StringDictionary();
            }
            return this._externalData.getOrAddWithFactory(key, factory);
        };
        /**
         * Remove an externaly attached data from the Engine instance
         * @param key the unique key that identifies the data
         * @return true if the data was successfully removed, false if it doesn't exist
         */
        Scene.prototype.removeExternalData = function (key) {
            return this._externalData.remove(key);
        };
        Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
            if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
                for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
                    var step = _a[_i];
                    step.action(mesh, subMesh);
                }
                var material = subMesh.getMaterial();
                if (material !== null && material !== undefined) {
                    // Render targets
                    if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
                        if (this._processedMaterials.indexOf(material) === -1) {
                            this._processedMaterials.push(material);
                            this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
                        }
                    }
                    // Dispatch
                    this._activeIndices.addCount(subMesh.indexCount, false);
                    this._renderingManager.dispatch(subMesh, mesh, material);
                }
            }
        };
        /**
         * Clear the processed materials smart array preventing retention point in material dispose.
         */
        Scene.prototype.freeProcessedMaterials = function () {
            this._processedMaterials.dispose();
        };
        /**
         * Clear the active meshes smart array preventing retention point in mesh dispose.
         */
        Scene.prototype.freeActiveMeshes = function () {
            this._activeMeshes.dispose();
            if (this.activeCamera && this.activeCamera._activeMeshes) {
                this.activeCamera._activeMeshes.dispose();
            }
            if (this.activeCameras) {
                for (var i = 0; i < this.activeCameras.length; i++) {
                    var activeCamera = this.activeCameras[i];
                    if (activeCamera && activeCamera._activeMeshes) {
                        activeCamera._activeMeshes.dispose();
                    }
                }
            }
        };
        /**
         * Clear the info related to rendering groups preventing retention points during dispose.
         */
        Scene.prototype.freeRenderingGroups = function () {
            if (this._renderingManager) {
                this._renderingManager.freeRenderingGroups();
            }
            if (this.textures) {
                for (var i = 0; i < this.textures.length; i++) {
                    var texture = this.textures[i];
                    if (texture && texture.renderList) {
                        texture.freeRenderingGroups();
                    }
                }
            }
        };
        /** @hidden */
        Scene.prototype._isInIntermediateRendering = function () {
            return this._intermediateRendering;
        };
        /**
         * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
         * @returns the current scene
         */
        Scene.prototype.freezeActiveMeshes = function () {
            if (!this.activeCamera) {
                return this;
            }
            if (!this._frustumPlanes) {
                this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
            }
            this._evaluateActiveMeshes();
            this._activeMeshesFrozen = true;
            return this;
        };
        /**
         * Use this function to restart evaluating active meshes on every frame
         * @returns the current scene
         */
        Scene.prototype.unfreezeActiveMeshes = function () {
            this._activeMeshesFrozen = false;
            return this;
        };
        Scene.prototype._evaluateActiveMeshes = function () {
            if (this._activeMeshesFrozen && this._activeMeshes.length) {
                return;
            }
            if (!this.activeCamera) {
                return;
            }
            this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
            this.activeCamera._activeMeshes.reset();
            this._activeMeshes.reset();
            this._renderingManager.reset();
            this._processedMaterials.reset();
            this._activeParticleSystems.reset();
            this._activeSkeletons.reset();
            this._softwareSkinnedMeshes.reset();
            for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
                var step = _a[_i];
                step.action();
            }
            // Determine mesh candidates
            var meshes = this.getActiveMeshCandidates();
            // Check each mesh
            var len = meshes.length;
            for (var i = 0; i < len; i++) {
                var mesh = meshes.data[i];
                if (mesh.isBlocked) {
                    continue;
                }
                this._totalVertices.addCount(mesh.getTotalVertices(), false);
                if (!mesh.isReady() || !mesh.isEnabled()) {
                    continue;
                }
                mesh.computeWorldMatrix();
                // Intersections
                if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
                    this._meshesForIntersections.pushNoDuplicate(mesh);
                }
                // Switch to current LOD
                var meshLOD = mesh.getLOD(this.activeCamera);
                if (meshLOD === undefined || meshLOD === null) {
                    continue;
                }
                mesh._preActivate();
                if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
                    this._activeMeshes.push(mesh);
                    this.activeCamera._activeMeshes.push(mesh);
                    mesh._activate(this._renderId);
                    if (meshLOD !== mesh) {
                        meshLOD._activate(this._renderId);
                    }
                    this._activeMesh(mesh, meshLOD);
                }
            }
            this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
            // Particle systems
            if (this.particlesEnabled) {
                this.onBeforeParticlesRenderingObservable.notifyObservers(this);
                for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
                    var particleSystem = this.particleSystems[particleIndex];
                    if (!particleSystem.isStarted() || !particleSystem.emitter) {
                        continue;
                    }
                    var emitter = particleSystem.emitter;
                    if (!emitter.position || emitter.isEnabled()) {
                        this._activeParticleSystems.push(particleSystem);
                        particleSystem.animate();
                        this._renderingManager.dispatchParticles(particleSystem);
                    }
                }
                this.onAfterParticlesRenderingObservable.notifyObservers(this);
            }
        };
        Scene.prototype._activeMesh = function (sourceMesh, mesh) {
            if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
                if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
                    mesh.skeleton.prepare();
                }
                if (!mesh.computeBonesUsingShaders) {
                    this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
                }
            }
            for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
                var step = _a[_i];
                step.action(sourceMesh, mesh);
            }
            if (mesh !== undefined && mesh !== null
                && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
                var subMeshes = this.getActiveSubMeshCandidates(mesh);
                var len = subMeshes.length;
                for (var i = 0; i < len; i++) {
                    var subMesh = subMeshes.data[i];
                    this._evaluateSubMesh(subMesh, mesh);
                }
            }
        };
        /**
         * Update the transform matrix to update from the current active camera
         * @param force defines a boolean used to force the update even if cache is up to date
         */
        Scene.prototype.updateTransformMatrix = function (force) {
            if (!this.activeCamera) {
                return;
            }
            this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
        };
        /**
         * Defines an alternate camera (used mostly in VR-like scenario where two cameras can render the same scene from a slightly different point of view)
         * @param alternateCamera defines the camera to use
         */
        Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
            this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
        };
        Scene.prototype._renderForCamera = function (camera, rigParent) {
            if (camera && camera._skipRendering) {
                return;
            }
            var engine = this._engine;
            this.activeCamera = camera;
            if (!this.activeCamera) {
                throw new Error("Active camera not set");
            }
            // Viewport
            engine.setViewport(this.activeCamera.viewport);
            // Camera
            this.resetCachedMaterial();
            this._renderId++;
            this.updateTransformMatrix();
            if (camera._alternateCamera) {
                this.updateAlternateTransformMatrix(camera._alternateCamera);
                this._alternateRendering = true;
            }
            this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
            // Meshes
            this._evaluateActiveMeshes();
            // Software skinning
            for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
                var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
                mesh.applySkeleton(mesh.skeleton);
            }
            // Render targets
            this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
            if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
                this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
            }
            if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
                this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
            }
            // Collects render targets from external components.
            for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
                var step = _a[_i];
                step.action(this._renderTargets);
            }
            if (this.renderTargetsEnabled) {
                this._intermediateRendering = true;
                if (this._renderTargets.length > 0) {
                    BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
                    for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
                        var renderTarget = this._renderTargets.data[renderIndex];
                        if (renderTarget._shouldRender()) {
                            this._renderId++;
                            var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
                            renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
                        }
                    }
                    BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
                    this._renderId++;
                }
                for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
                    var step = _c[_b];
                    step.action(this.activeCamera);
                }
                this._intermediateRendering = false;
                engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
            }
            this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
            // Prepare Frame
            if (this.postProcessManager) {
                this.postProcessManager._prepareFrame();
            }
            // Before Camera Draw
            for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
                var step = _e[_d];
                step.action(this.activeCamera);
            }
            // Render
            this.onBeforeDrawPhaseObservable.notifyObservers(this);
            this._renderingManager.render(null, null, true, true);
            this.onAfterDrawPhaseObservable.notifyObservers(this);
            // After Camera Draw
            for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
                var step = _g[_f];
                step.action(this.activeCamera);
            }
            // Finalize frame
            if (this.postProcessManager) {
                this.postProcessManager._finalizeFrame(camera.isIntermediate);
            }
            // Reset some special arrays
            this._renderTargets.reset();
            this._alternateRendering = false;
            this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
        };
        Scene.prototype._processSubCameras = function (camera) {
            if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
                this._renderForCamera(camera);
                return;
            }
            // rig cameras
            for (var index = 0; index < camera._rigCameras.length; index++) {
                this._renderForCamera(camera._rigCameras[index], camera);
            }
            this.activeCamera = camera;
            this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
        };
        Scene.prototype._checkIntersections = function () {
            for (var index = 0; index < this._meshesForIntersections.length; index++) {
                var sourceMesh = this._meshesForIntersections.data[index];
                if (!sourceMesh.actionManager) {
                    continue;
                }
                for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
                    var action = sourceMesh.actionManager.actions[actionIndex];
                    if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                        var parameters = action.getTriggerParameter();
                        var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
                        var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
                        var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
                        if (areIntersecting && currentIntersectionInProgress === -1) {
                            if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
                                action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
                                sourceMesh._intersectionsInProgress.push(otherMesh);
                            }
                            else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                                sourceMesh._intersectionsInProgress.push(otherMesh);
                            }
                        }
                        else if (!areIntersecting && currentIntersectionInProgress > -1) {
                            //They intersected, and now they don't.
                            //is this trigger an exit trigger? execute an event.
                            if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                                action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
                            }
                            //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
                            if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
                                var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
                                return otherMesh === parameterMesh;
                            }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
                                sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
                            }
                        }
                    }
                }
            }
        };
        /** @hidden */
        Scene.prototype._advancePhysicsEngineStep = function (step) {
            // Do nothing. Code will be replaced if physics engine component is referenced
        };
        /**
         * Render the scene
         * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
         */
        Scene.prototype.render = function (updateCameras) {
            if (updateCameras === void 0) { updateCameras = true; }
            if (this.isDisposed) {
                return;
            }
            this._frameId++;
            // Register components that have been associated lately to the scene.
            this._registerTransientComponents();
            this._activeParticles.fetchNewFrame();
            this._totalVertices.fetchNewFrame();
            this._activeIndices.fetchNewFrame();
            this._activeBones.fetchNewFrame();
            this._meshesForIntersections.reset();
            this.resetCachedMaterial();
            this.onBeforeAnimationsObservable.notifyObservers(this);
            // Actions
            if (this.actionManager) {
                this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
            }
            if (this._engine.isDeterministicLockStep()) {
                var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
                var defaultFPS = (60.0 / 1000.0);
                var defaultFrameTime = this.getDeterministicFrameTime();
                var stepsTaken = 0;
                var maxSubSteps = this._engine.getLockstepMaxSteps();
                var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
                internalSteps = Math.min(internalSteps, maxSubSteps);
                do {
                    this.onBeforeStepObservable.notifyObservers(this);
                    // Animations
                    this._animationRatio = defaultFrameTime * defaultFPS;
                    this._animate();
                    this.onAfterAnimationsObservable.notifyObservers(this);
                    // Physics
                    this._advancePhysicsEngineStep(defaultFrameTime);
                    this.onAfterStepObservable.notifyObservers(this);
                    this._currentStepId++;
                    stepsTaken++;
                    deltaTime -= defaultFrameTime;
                } while (deltaTime > 0 && stepsTaken < internalSteps);
                this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
            }
            else {
                // Animations
                var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
                this._animationRatio = deltaTime * (60.0 / 1000.0);
                this._animate();
                this.onAfterAnimationsObservable.notifyObservers(this);
                // Physics
                this._advancePhysicsEngineStep(deltaTime);
            }
            // Before camera update steps
            for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
                var step = _a[_i];
                step.action();
            }
            // Update Cameras
            if (updateCameras) {
                if (this.activeCameras.length > 0) {
                    for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
                        var camera = this.activeCameras[cameraIndex];
                        camera.update();
                        if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
                            // rig cameras
                            for (var index = 0; index < camera._rigCameras.length; index++) {
                                camera._rigCameras[index].update();
                            }
                        }
                    }
                }
                else if (this.activeCamera) {
                    this.activeCamera.update();
                    if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
                        // rig cameras
                        for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
                            this.activeCamera._rigCameras[index].update();
                        }
                    }
                }
            }
            // Before render
            this.onBeforeRenderObservable.notifyObservers(this);
            // Customs render targets
            this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
            var engine = this.getEngine();
            var currentActiveCamera = this.activeCamera;
            if (this.renderTargetsEnabled) {
                BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
                this._intermediateRendering = true;
                for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
                    var renderTarget = this.customRenderTargets[customIndex];
                    if (renderTarget._shouldRender()) {
                        this._renderId++;
                        this.activeCamera = renderTarget.activeCamera || this.activeCamera;
                        if (!this.activeCamera) {
                            throw new Error("Active camera not set");
                        }
                        // Viewport
                        engine.setViewport(this.activeCamera.viewport);
                        // Camera
                        this.updateTransformMatrix();
                        renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
                this._intermediateRendering = false;
                this._renderId++;
            }
            // Restore back buffer
            if (this.customRenderTargets.length > 0) {
                engine.restoreDefaultFramebuffer();
            }
            this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
            this.activeCamera = currentActiveCamera;
            for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
                var step = _c[_b];
                step.action();
            }
            // Clear
            if (this.autoClearDepthAndStencil || this.autoClear) {
                this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
            }
            // Collects render targets from external components.
            for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
                var step = _e[_d];
                step.action(this._renderTargets);
            }
            // Multi-cameras?
            if (this.activeCameras.length > 0) {
                for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
                    if (cameraIndex > 0) {
                        this._engine.clear(null, false, true, true);
                    }
                    this._processSubCameras(this.activeCameras[cameraIndex]);
                }
            }
            else {
                if (!this.activeCamera) {
                    throw new Error("No camera defined");
                }
                this._processSubCameras(this.activeCamera);
            }
            // Intersection checks
            this._checkIntersections();
            // Executes the after render stage actions.
            for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
                var step = _g[_f];
                step.action();
            }
            // After render
            if (this.afterRender) {
                this.afterRender();
            }
            this.onAfterRenderObservable.notifyObservers(this);
            // Cleaning
            if (this._toBeDisposed.length) {
                for (var index = 0; index < this._toBeDisposed.length; index++) {
                    var data = this._toBeDisposed[index];
                    if (data) {
                        data.dispose();
                    }
                }
                this._toBeDisposed = [];
            }
            if (this.dumpNextRenderTargets) {
                this.dumpNextRenderTargets = false;
            }
            this._activeBones.addCount(0, true);
            this._activeIndices.addCount(0, true);
            this._activeParticles.addCount(0, true);
        };
        /**
         * Freeze all materials
         * A frozen material will not be updatable but should be faster to render
         */
        Scene.prototype.freezeMaterials = function () {
            for (var i = 0; i < this.materials.length; i++) {
                this.materials[i].freeze();
            }
        };
        /**
         * Unfreeze all materials
         * A frozen material will not be updatable but should be faster to render
         */
        Scene.prototype.unfreezeMaterials = function () {
            for (var i = 0; i < this.materials.length; i++) {
                this.materials[i].unfreeze();
            }
        };
        /**
         * Releases all held ressources
         */
        Scene.prototype.dispose = function () {
            this.beforeRender = null;
            this.afterRender = null;
            this.skeletons = [];
            this.morphTargetManagers = [];
            this._transientComponents = [];
            this._isReadyForMeshStage.clear();
            this._beforeEvaluateActiveMeshStage.clear();
            this._evaluateSubMeshStage.clear();
            this._activeMeshStage.clear();
            this._cameraDrawRenderTargetStage.clear();
            this._beforeCameraDrawStage.clear();
            this._beforeRenderingGroupDrawStage.clear();
            this._beforeRenderingMeshStage.clear();
            this._afterRenderingMeshStage.clear();
            this._afterRenderingGroupDrawStage.clear();
            this._afterCameraDrawStage.clear();
            this._afterRenderStage.clear();
            this._beforeCameraUpdateStage.clear();
            this._beforeClearStage.clear();
            this._gatherRenderTargetsStage.clear();
            this._gatherActiveCameraRenderTargetsStage.clear();
            this._pointerMoveStage.clear();
            this._pointerDownStage.clear();
            this._pointerUpStage.clear();
            for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
                var component = _a[_i];
                component.dispose();
            }
            this.importedMeshesFiles = new Array();
            this.stopAllAnimations();
            this.resetCachedMaterial();
            // Smart arrays
            if (this.activeCamera) {
                this.activeCamera._activeMeshes.dispose();
                this.activeCamera = null;
            }
            this._activeMeshes.dispose();
            this._renderingManager.dispose();
            this._processedMaterials.dispose();
            this._activeParticleSystems.dispose();
            this._activeSkeletons.dispose();
            this._softwareSkinnedMeshes.dispose();
            this._renderTargets.dispose();
            this._registeredForLateAnimationBindings.dispose();
            this._meshesForIntersections.dispose();
            this._toBeDisposed = [];
            // Abort active requests
            for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
                var request = _c[_b];
                request.abort();
            }
            // Events
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onBeforeRenderObservable.clear();
            this.onAfterRenderObservable.clear();
            this.onBeforeRenderTargetsRenderObservable.clear();
            this.onAfterRenderTargetsRenderObservable.clear();
            this.onAfterStepObservable.clear();
            this.onBeforeStepObservable.clear();
            this.onBeforeActiveMeshesEvaluationObservable.clear();
            this.onAfterActiveMeshesEvaluationObservable.clear();
            this.onBeforeParticlesRenderingObservable.clear();
            this.onAfterParticlesRenderingObservable.clear();
            this.onBeforeDrawPhaseObservable.clear();
            this.onAfterDrawPhaseObservable.clear();
            this.onBeforeAnimationsObservable.clear();
            this.onAfterAnimationsObservable.clear();
            this.onDataLoadedObservable.clear();
            this.onBeforeRenderingGroupObservable.clear();
            this.onAfterRenderingGroupObservable.clear();
            this.onMeshImportedObservable.clear();
            this.onBeforeCameraRenderObservable.clear();
            this.onAfterCameraRenderObservable.clear();
            this.onReadyObservable.clear();
            this.onNewCameraAddedObservable.clear();
            this.onCameraRemovedObservable.clear();
            this.onNewLightAddedObservable.clear();
            this.onLightRemovedObservable.clear();
            this.onNewGeometryAddedObservable.clear();
            this.onGeometryRemovedObservable.clear();
            this.onNewTransformNodeAddedObservable.clear();
            this.onTransformNodeRemovedObservable.clear();
            this.onNewMeshAddedObservable.clear();
            this.onMeshRemovedObservable.clear();
            this.onNewMaterialAddedObservable.clear();
            this.onMaterialRemovedObservable.clear();
            this.onNewTextureAddedObservable.clear();
            this.onTextureRemovedObservable.clear();
            this.onPrePointerObservable.clear();
            this.onPointerObservable.clear();
            this.onPreKeyboardObservable.clear();
            this.onKeyboardObservable.clear();
            this.detachControl();
            // Detach cameras
            var canvas = this._engine.getRenderingCanvas();
            if (canvas) {
                var index;
                for (index = 0; index < this.cameras.length; index++) {
                    this.cameras[index].detachControl(canvas);
                }
            }
            // Release animation groups
            while (this.animationGroups.length) {
                this.animationGroups[0].dispose();
            }
            // Release lights
            while (this.lights.length) {
                this.lights[0].dispose();
            }
            // Release meshes
            while (this.meshes.length) {
                this.meshes[0].dispose(true);
            }
            while (this.transformNodes.length) {
                this.removeTransformNode(this.transformNodes[0]);
            }
            // Release cameras
            while (this.cameras.length) {
                this.cameras[0].dispose();
            }
            // Release materials
            if (this.defaultMaterial) {
                this.defaultMaterial.dispose();
            }
            while (this.multiMaterials.length) {
                this.multiMaterials[0].dispose();
            }
            while (this.materials.length) {
                this.materials[0].dispose();
            }
            // Release particles
            while (this.particleSystems.length) {
                this.particleSystems[0].dispose();
            }
            // Release postProcesses
            while (this.postProcesses.length) {
                this.postProcesses[0].dispose();
            }
            // Release textures
            while (this.textures.length) {
                this.textures[0].dispose();
            }
            // Release UBO
            this._sceneUbo.dispose();
            if (this._alternateSceneUbo) {
                this._alternateSceneUbo.dispose();
            }
            // Post-processes
            this.postProcessManager.dispose();
            // Remove from engine
            index = this._engine.scenes.indexOf(this);
            if (index > -1) {
                this._engine.scenes.splice(index, 1);
            }
            this._engine.wipeCaches(true);
            this._isDisposed = true;
        };
        Object.defineProperty(Scene.prototype, "isDisposed", {
            /**
             * Gets if the scene is already disposed
             */
            get: function () {
                return this._isDisposed;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Call this function to reduce memory footprint of the scene.
         * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
         */
        Scene.prototype.clearCachedVertexData = function () {
            for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
                var mesh = this.meshes[meshIndex];
                var geometry = mesh.geometry;
                if (geometry) {
                    geometry._indices = [];
                    for (var vbName in geometry._vertexBuffers) {
                        if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
                            continue;
                        }
                        geometry._vertexBuffers[vbName]._buffer._data = null;
                    }
                }
            }
        };
        /**
         * This function will remove the local cached buffer data from texture.
         * It will save memory but will prevent the texture from being rebuilt
         */
        Scene.prototype.cleanCachedTextureBuffer = function () {
            for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
                var baseTexture = _a[_i];
                var buffer = baseTexture._buffer;
                if (buffer) {
                    baseTexture._buffer = null;
                }
            }
        };
        /**
         * Get the world extend vectors with an optional filter
         *
         * @param filterPredicate the predicate - which meshes should be included when calculating the world size
         * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
         */
        Scene.prototype.getWorldExtends = function (filterPredicate) {
            var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            filterPredicate = filterPredicate || (function () { return true; });
            this.meshes.filter(filterPredicate).forEach(function (mesh) {
                mesh.computeWorldMatrix(true);
                if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
                    return;
                }
                var boundingInfo = mesh.getBoundingInfo();
                var minBox = boundingInfo.boundingBox.minimumWorld;
                var maxBox = boundingInfo.boundingBox.maximumWorld;
                BABYLON.Tools.CheckExtends(minBox, min, max);
                BABYLON.Tools.CheckExtends(maxBox, min, max);
            });
            return {
                min: min,
                max: max
            };
        };
        // Picking
        /**
         * Creates a ray that can be used to pick in the scene
         * @param x defines the x coordinate of the origin (on-screen)
         * @param y defines the y coordinate of the origin (on-screen)
         * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
         * @param camera defines the camera to use for the picking
         * @param cameraViewSpace defines if picking will be done in view space (false by default)
         * @returns a Ray
         */
        Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
            if (cameraViewSpace === void 0) { cameraViewSpace = false; }
            var result = BABYLON.Ray.Zero();
            this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
            return result;
        };
        /**
         * Creates a ray that can be used to pick in the scene
         * @param x defines the x coordinate of the origin (on-screen)
         * @param y defines the y coordinate of the origin (on-screen)
         * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
         * @param result defines the ray where to store the picking ray
         * @param camera defines the camera to use for the picking
         * @param cameraViewSpace defines if picking will be done in view space (false by default)
         * @returns the current scene
         */
        Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
            if (cameraViewSpace === void 0) { cameraViewSpace = false; }
            var engine = this._engine;
            if (!camera) {
                if (!this.activeCamera) {
                    throw new Error("Active camera not set");
                }
                camera = this.activeCamera;
            }
            var cameraViewport = camera.viewport;
            var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            // Moving coordinates to local viewport world
            x = x / this._engine.getHardwareScalingLevel() - viewport.x;
            y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
            result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
            return this;
        };
        /**
         * Creates a ray that can be used to pick in the scene
         * @param x defines the x coordinate of the origin (on-screen)
         * @param y defines the y coordinate of the origin (on-screen)
         * @param camera defines the camera to use for the picking
         * @returns a Ray
         */
        Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
            var result = BABYLON.Ray.Zero();
            this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
            return result;
        };
        /**
         * Creates a ray that can be used to pick in the scene
         * @param x defines the x coordinate of the origin (on-screen)
         * @param y defines the y coordinate of the origin (on-screen)
         * @param result defines the ray where to store the picking ray
         * @param camera defines the camera to use for the picking
         * @returns the current scene
         */
        Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
            if (!BABYLON.PickingInfo) {
                return this;
            }
            var engine = this._engine;
            if (!camera) {
                if (!this.activeCamera) {
                    throw new Error("Active camera not set");
                }
                camera = this.activeCamera;
            }
            var cameraViewport = camera.viewport;
            var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            var identity = BABYLON.Matrix.Identity();
            // Moving coordinates to local viewport world
            x = x / this._engine.getHardwareScalingLevel() - viewport.x;
            y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
            result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
            return this;
        };
        Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
            if (!BABYLON.PickingInfo) {
                return null;
            }
            var pickingInfo = null;
            for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
                var mesh = this.meshes[meshIndex];
                if (predicate) {
                    if (!predicate(mesh)) {
                        continue;
                    }
                }
                else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
                    continue;
                }
                var world = mesh.getWorldMatrix();
                var ray = rayFunction(world);
                var result = mesh.intersects(ray, fastCheck);
                if (!result || !result.hit) {
                    continue;
                }
                if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
                    continue;
                }
                pickingInfo = result;
                if (fastCheck) {
                    break;
                }
            }
            return pickingInfo || new BABYLON.PickingInfo();
        };
        Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
            if (!BABYLON.PickingInfo) {
                return null;
            }
            var pickingInfos = new Array();
            for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
                var mesh = this.meshes[meshIndex];
                if (predicate) {
                    if (!predicate(mesh)) {
                        continue;
                    }
                }
                else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
                    continue;
                }
                var world = mesh.getWorldMatrix();
                var ray = rayFunction(world);
                var result = mesh.intersects(ray, false);
                if (!result || !result.hit) {
                    continue;
                }
                pickingInfos.push(result);
            }
            return pickingInfos;
        };
        /** Launch a ray to try to pick a mesh in the scene
         * @param x position on screen
         * @param y position on screen
         * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
         * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
         * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
         * @returns a PickingInfo
         */
        Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
            var _this = this;
            if (!BABYLON.PickingInfo) {
                return null;
            }
            var result = this._internalPick(function (world) {
                _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
                return _this._tempPickingRay;
            }, predicate, fastCheck);
            if (result) {
                result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
            }
            return result;
        };
        /** Use the given ray to pick a mesh in the scene
         * @param ray The ray to use to pick meshes
         * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true
         * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
         * @returns a PickingInfo
         */
        Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
            var _this = this;
            var result = this._internalPick(function (world) {
                if (!_this._pickWithRayInverseMatrix) {
                    _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
                }
                world.invertToRef(_this._pickWithRayInverseMatrix);
                if (!_this._cachedRayForTransform) {
                    _this._cachedRayForTransform = BABYLON.Ray.Zero();
                }
                BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
                return _this._cachedRayForTransform;
            }, predicate, fastCheck);
            if (result) {
                result.ray = ray;
            }
            return result;
        };
        /**
         * Launch a ray to try to pick a mesh in the scene
         * @param x X position on screen
         * @param y Y position on screen
         * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
         * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
         * @returns an array of PickingInfo
         */
        Scene.prototype.multiPick = function (x, y, predicate, camera) {
            var _this = this;
            return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
        };
        /**
         * Launch a ray to try to pick a mesh in the scene
         * @param ray Ray to use
         * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true
         * @returns an array of PickingInfo
         */
        Scene.prototype.multiPickWithRay = function (ray, predicate) {
            var _this = this;
            return this._internalMultiPick(function (world) {
                if (!_this._pickWithRayInverseMatrix) {
                    _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
                }
                world.invertToRef(_this._pickWithRayInverseMatrix);
                if (!_this._cachedRayForTransform) {
                    _this._cachedRayForTransform = BABYLON.Ray.Zero();
                }
                BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
                return _this._cachedRayForTransform;
            }, predicate);
        };
        /**
         * Force the value of meshUnderPointer
         * @param mesh defines the mesh to use
         */
        Scene.prototype.setPointerOverMesh = function (mesh) {
            if (this._pointerOverMesh === mesh) {
                return;
            }
            if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
                this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
            }
            this._pointerOverMesh = mesh;
            if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
                this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
            }
        };
        /**
         * Gets the mesh under the pointer
         * @returns a Mesh or null if no mesh is under the pointer
         */
        Scene.prototype.getPointerOverMesh = function () {
            return this._pointerOverMesh;
        };
        // Misc.
        /** @hidden */
        Scene.prototype._rebuildGeometries = function () {
            for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
                var geometry = _a[_i];
                geometry._rebuild();
            }
            for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
                var mesh = _c[_b];
                mesh._rebuild();
            }
            if (this.postProcessManager) {
                this.postProcessManager._rebuild();
            }
            for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
                var component = _e[_d];
                component.rebuild();
            }
            for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
                var system = _g[_f];
                system.rebuild();
            }
        };
        /** @hidden */
        Scene.prototype._rebuildTextures = function () {
            for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
                var texture = _a[_i];
                texture._rebuild();
            }
            this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
        };
        // Tags
        Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
            if (tagsQuery === undefined) {
                // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
                return list;
            }
            var listByTags = [];
            forEach = forEach || (function (item) { return; });
            for (var i in list) {
                var item = list[i];
                if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
                    listByTags.push(item);
                    forEach(item);
                }
            }
            return listByTags;
        };
        /**
         * Get a list of meshes by tags
         * @param tagsQuery defines the tags query to use
         * @param forEach defines a predicate used to filter results
         * @returns an array of Mesh
         */
        Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.meshes, tagsQuery, forEach);
        };
        /**
         * Get a list of cameras by tags
         * @param tagsQuery defines the tags query to use
         * @param forEach defines a predicate used to filter results
         * @returns an array of Camera
         */
        Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.cameras, tagsQuery, forEach);
        };
        /**
         * Get a list of lights by tags
         * @param tagsQuery defines the tags query to use
         * @param forEach defines a predicate used to filter results
         * @returns an array of Light
         */
        Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.lights, tagsQuery, forEach);
        };
        /**
         * Get a list of materials by tags
         * @param tagsQuery defines the tags query to use
         * @param forEach defines a predicate used to filter results
         * @returns an array of Material
         */
        Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
            return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
        };
        /**
         * Overrides the default sort function applied in the renderging group to prepare the meshes.
         * This allowed control for front to back rendering or reversly depending of the special needs.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
         * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
         * @param transparentSortCompareFn The transparent queue comparison function use to sort.
         */
        Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         * @param depth Automatically clears depth between groups if true and autoClear is true.
         * @param stencil Automatically clears stencil between groups if true and autoClear is true.
         */
        Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
            if (depth === void 0) { depth = true; }
            if (stencil === void 0) { stencil = true; }
            this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
        };
        /**
         * Gets the current auto clear configuration for one rendering group of the rendering
         * manager.
         * @param index the rendering group index to get the information for
         * @returns The auto clear setup for the requested rendering group
         */
        Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
            return this._renderingManager.getAutoClearDepthStencilSetup(index);
        };
        Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
            /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
            get: function () {
                return this._blockMaterialDirtyMechanism;
            },
            set: function (value) {
                if (this._blockMaterialDirtyMechanism === value) {
                    return;
                }
                this._blockMaterialDirtyMechanism = value;
                if (!value) { // Do a complete update
                    this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Will flag all materials as dirty to trigger new shader compilation
         * @param flag defines the flag used to specify which material part must be marked as dirty
         * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
         */
        Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
            if (this._blockMaterialDirtyMechanism) {
                return;
            }
            for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
                var material = _a[_i];
                if (predicate && !predicate(material)) {
                    continue;
                }
                material.markAsDirty(flag);
            }
        };
        /** @hidden */
        Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
            var _this = this;
            var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
            this._activeRequests.push(request);
            request.onCompleteObservable.add(function (request) {
                _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
            });
            return request;
        };
        /** @hidden */
        Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                _this._loadFile(url, function (data) {
                    resolve(data);
                }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
                    reject(exception);
                });
            });
        };
        // Statics
        Scene._uniqueIdCounter = 0;
        /** The fog is deactivated */
        Scene.FOGMODE_NONE = 0;
        /** The fog density is following an exponential function */
        Scene.FOGMODE_EXP = 1;
        /** The fog density is following an exponential function faster than FOGMODE_EXP */
        Scene.FOGMODE_EXP2 = 2;
        /** The fog density is following a linear function. */
        Scene.FOGMODE_LINEAR = 3;
        /**
         * Gets or sets the minimum deltatime when deterministic lock step is enabled
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         */
        Scene.MinDeltaTime = 1.0;
        /**
         * Gets or sets the maximum deltatime when deterministic lock step is enabled
         * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         */
        Scene.MaxDeltaTime = 1000.0;
        /** The distance in pixel that you have to move to prevent some events */
        Scene.DragMovementThreshold = 10; // in pixels
        /** Time in milliseconds to wait to raise long press events if button is still pressed */
        Scene.LongPressDelay = 500; // in milliseconds
        /** Time in milliseconds with two consecutive clicks will be considered as a double click */
        Scene.DoubleClickDelay = 300; // in milliseconds
        /** If you need to check double click without raising a single click at first click, enable this flag */
        Scene.ExclusiveDoubleClickMode = false;
        return Scene;
    }(BABYLON.AbstractScene));
    BABYLON.Scene = Scene;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.scene.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Set of assets to keep when moving a scene into an asset container.
     */
    var KeepAssets = /** @class */ (function (_super) {
        __extends(KeepAssets, _super);
        function KeepAssets() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return KeepAssets;
    }(BABYLON.AbstractScene));
    BABYLON.KeepAssets = KeepAssets;
    /**
     * Container with a set of assets that can be added or removed from a scene.
     */
    var AssetContainer = /** @class */ (function (_super) {
        __extends(AssetContainer, _super);
        /**
         * Instantiates an AssetContainer.
         * @param scene The scene the AssetContainer belongs to.
         */
        function AssetContainer(scene) {
            var _this = _super.call(this) || this;
            _this.scene = scene;
            return _this;
        }
        /**
         * Adds all the assets from the container to the scene.
         */
        AssetContainer.prototype.addAllToScene = function () {
            var _this = this;
            this.cameras.forEach(function (o) {
                _this.scene.addCamera(o);
            });
            this.lights.forEach(function (o) {
                _this.scene.addLight(o);
            });
            this.meshes.forEach(function (o) {
                _this.scene.addMesh(o);
            });
            this.skeletons.forEach(function (o) {
                _this.scene.addSkeleton(o);
            });
            this.animations.forEach(function (o) {
                _this.scene.addAnimation(o);
            });
            this.animationGroups.forEach(function (o) {
                _this.scene.addAnimationGroup(o);
            });
            this.multiMaterials.forEach(function (o) {
                _this.scene.addMultiMaterial(o);
            });
            this.materials.forEach(function (o) {
                _this.scene.addMaterial(o);
            });
            this.morphTargetManagers.forEach(function (o) {
                _this.scene.addMorphTargetManager(o);
            });
            this.geometries.forEach(function (o) {
                _this.scene.addGeometry(o);
            });
            this.transformNodes.forEach(function (o) {
                _this.scene.addTransformNode(o);
            });
            this.actionManagers.forEach(function (o) {
                _this.scene.addActionManager(o);
            });
            this.textures.forEach(function (o) {
                _this.scene.addTexture(o);
            });
            for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
                var component = _a[_i];
                component.addFromContainer(this.scene);
            }
        };
        /**
         * Removes all the assets in the container from the scene
         */
        AssetContainer.prototype.removeAllFromScene = function () {
            var _this = this;
            this.cameras.forEach(function (o) {
                _this.scene.removeCamera(o);
            });
            this.lights.forEach(function (o) {
                _this.scene.removeLight(o);
            });
            this.meshes.forEach(function (o) {
                _this.scene.removeMesh(o);
            });
            this.skeletons.forEach(function (o) {
                _this.scene.removeSkeleton(o);
            });
            this.animations.forEach(function (o) {
                _this.scene.removeAnimation(o);
            });
            this.animationGroups.forEach(function (o) {
                _this.scene.removeAnimationGroup(o);
            });
            this.multiMaterials.forEach(function (o) {
                _this.scene.removeMultiMaterial(o);
            });
            this.materials.forEach(function (o) {
                _this.scene.removeMaterial(o);
            });
            this.morphTargetManagers.forEach(function (o) {
                _this.scene.removeMorphTargetManager(o);
            });
            this.geometries.forEach(function (o) {
                _this.scene.removeGeometry(o);
            });
            this.transformNodes.forEach(function (o) {
                _this.scene.removeTransformNode(o);
            });
            this.actionManagers.forEach(function (o) {
                _this.scene.removeActionManager(o);
            });
            this.textures.forEach(function (o) {
                _this.scene.removeTexture(o);
            });
            for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
                var component = _a[_i];
                component.removeFromContainer(this.scene);
            }
        };
        AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
            if (!sourceAssets) {
                return;
            }
            for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
                var asset = sourceAssets_1[_i];
                var move = true;
                if (keepAssets) {
                    for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
                        var keepAsset = keepAssets_1[_a];
                        if (asset === keepAsset) {
                            move = false;
                            break;
                        }
                    }
                }
                if (move) {
                    targetAssets.push(asset);
                }
            }
        };
        /**
         * Removes all the assets contained in the scene and adds them to the container.
         * @param keepAssets Set of assets to keep in the scene. (default: empty)
         */
        AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
            if (keepAssets === undefined) {
                keepAssets = new KeepAssets();
            }
            for (var key in this) {
                if (this.hasOwnProperty(key)) {
                    this[key] = this[key] || [];
                    this._moveAssets(this.scene[key], this[key], keepAssets[key]);
                }
            }
            this.removeAllFromScene();
        };
        /**
         * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
         * @returns the root mesh
         */
        AssetContainer.prototype.createRootMesh = function () {
            var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
            this.meshes.forEach(function (m) {
                if (!m.parent) {
                    rootMesh.addChild(m);
                }
            });
            this.meshes.unshift(rootMesh);
            return rootMesh;
        };
        return AssetContainer;
    }(BABYLON.AbstractScene));
    BABYLON.AssetContainer = AssetContainer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.assetContainer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store data that will be store in GPU memory
     */
    var Buffer = /** @class */ (function () {
        /**
         * Constructor
         * @param engine the engine
         * @param data the data to use for this buffer
         * @param updatable whether the data is updatable
         * @param stride the stride (optional)
         * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
         * @param instanced whether the buffer is instanced (optional)
         * @param useBytes set to true if the stride in in bytes (optional)
         */
        function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
            if (stride === void 0) { stride = 0; }
            if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
            if (instanced === void 0) { instanced = false; }
            if (useBytes === void 0) { useBytes = false; }
            if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
                this._engine = engine.getScene().getEngine();
            }
            else {
                this._engine = engine;
            }
            this._updatable = updatable;
            this._instanced = instanced;
            this._data = data;
            this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
            if (!postponeInternalCreation) { // by default
                this.create();
            }
        }
        /**
         * Create a new VertexBuffer based on the current buffer
         * @param kind defines the vertex buffer kind (position, normal, etc.)
         * @param offset defines offset in the buffer (0 by default)
         * @param size defines the size in floats of attributes (position is 3 for instance)
         * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
         * @param instanced defines if the vertex buffer contains indexed data
         * @param useBytes defines if the offset and stride are in bytes
         * @returns the new vertex buffer
         */
        Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
            if (useBytes === void 0) { useBytes = false; }
            var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
            var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
            // a lot of these parameters are ignored as they are overriden by the buffer
            return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
        };
        // Properties
        /**
         * Gets a boolean indicating if the Buffer is updatable?
         * @returns true if the buffer is updatable
         */
        Buffer.prototype.isUpdatable = function () {
            return this._updatable;
        };
        /**
         * Gets current buffer's data
         * @returns a DataArray or null
         */
        Buffer.prototype.getData = function () {
            return this._data;
        };
        /**
         * Gets underlying native buffer
         * @returns underlying native buffer
         */
        Buffer.prototype.getBuffer = function () {
            return this._buffer;
        };
        /**
         * Gets the stride in float32 units (i.e. byte stride / 4).
         * May not be an integer if the byte stride is not divisible by 4.
         * DEPRECATED. Use byteStride instead.
         * @returns the stride in float32 units
         */
        Buffer.prototype.getStrideSize = function () {
            return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
        };
        // Methods
        /**
         * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
         * @param data defines the data to store
         */
        Buffer.prototype.create = function (data) {
            if (data === void 0) { data = null; }
            if (!data && this._buffer) {
                return; // nothing to do
            }
            data = data || this._data;
            if (!data) {
                return;
            }
            if (!this._buffer) { // create buffer
                if (this._updatable) {
                    this._buffer = this._engine.createDynamicVertexBuffer(data);
                    this._data = data;
                }
                else {
                    this._buffer = this._engine.createVertexBuffer(data);
                }
            }
            else if (this._updatable) { // update buffer
                this._engine.updateDynamicVertexBuffer(this._buffer, data);
                this._data = data;
            }
        };
        /** @hidden */
        Buffer.prototype._rebuild = function () {
            this._buffer = null;
            this.create(this._data);
        };
        /**
         * Update current buffer data
         * @param data defines the data to store
         */
        Buffer.prototype.update = function (data) {
            this.create(data);
        };
        /**
         * Updates the data directly.
         * @param data the new data
         * @param offset the new offset
         * @param vertexCount the vertex count (optional)
         * @param useBytes set to true if the offset is in bytes
         */
        Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
            if (useBytes === void 0) { useBytes = false; }
            if (!this._buffer) {
                return;
            }
            if (this._updatable) { // update buffer
                this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
                this._data = null;
            }
        };
        /**
         * Release all resources
         */
        Buffer.prototype.dispose = function () {
            if (!this._buffer) {
                return;
            }
            if (this._engine._releaseBuffer(this._buffer)) {
                this._buffer = null;
            }
        };
        return Buffer;
    }());
    BABYLON.Buffer = Buffer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.buffer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Specialized buffer used to store vertex data
     */
    var VertexBuffer = /** @class */ (function () {
        /**
         * Constructor
         * @param engine the engine
         * @param data the data to use for this vertex buffer
         * @param kind the vertex buffer kind
         * @param updatable whether the data is updatable
         * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
         * @param stride the stride (optional)
         * @param instanced whether the buffer is instanced (optional)
         * @param offset the offset of the data (optional)
         * @param size the number of components (optional)
         * @param type the type of the component (optional)
         * @param normalized whether the data contains normalized data (optional)
         * @param useBytes set to true if stride and offset are in bytes (optional)
         */
        function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
            if (normalized === void 0) { normalized = false; }
            if (useBytes === void 0) { useBytes = false; }
            if (data instanceof BABYLON.Buffer) {
                this._buffer = data;
                this._ownsBuffer = false;
            }
            else {
                this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
                this._ownsBuffer = true;
            }
            this._kind = kind;
            if (type == undefined) {
                var data_1 = this.getData();
                this.type = VertexBuffer.FLOAT;
                if (data_1 instanceof Int8Array) {
                    this.type = VertexBuffer.BYTE;
                }
                else if (data_1 instanceof Uint8Array) {
                    this.type = VertexBuffer.UNSIGNED_BYTE;
                }
                else if (data_1 instanceof Int16Array) {
                    this.type = VertexBuffer.SHORT;
                }
                else if (data_1 instanceof Uint16Array) {
                    this.type = VertexBuffer.UNSIGNED_SHORT;
                }
                else if (data_1 instanceof Int32Array) {
                    this.type = VertexBuffer.INT;
                }
                else if (data_1 instanceof Uint32Array) {
                    this.type = VertexBuffer.UNSIGNED_INT;
                }
            }
            else {
                this.type = type;
            }
            var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
            if (useBytes) {
                this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
                this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
                this.byteOffset = offset || 0;
            }
            else {
                this._size = size || stride || VertexBuffer.DeduceStride(kind);
                this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
                this.byteOffset = (offset || 0) * typeByteLength;
            }
            this.normalized = normalized;
            this._instanced = instanced !== undefined ? instanced : false;
            this._instanceDivisor = instanced ? 1 : 0;
        }
        Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
            /**
             * Gets or sets the instance divisor when in instanced mode
             */
            get: function () {
                return this._instanceDivisor;
            },
            set: function (value) {
                this._instanceDivisor = value;
                if (value == 0) {
                    this._instanced = false;
                }
                else {
                    this._instanced = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        VertexBuffer.prototype._rebuild = function () {
            if (!this._buffer) {
                return;
            }
            this._buffer._rebuild();
        };
        /**
         * Returns the kind of the VertexBuffer (string)
         * @returns a string
         */
        VertexBuffer.prototype.getKind = function () {
            return this._kind;
        };
        // Properties
        /**
         * Gets a boolean indicating if the VertexBuffer is updatable?
         * @returns true if the buffer is updatable
         */
        VertexBuffer.prototype.isUpdatable = function () {
            return this._buffer.isUpdatable();
        };
        /**
         * Gets current buffer's data
         * @returns a DataArray or null
         */
        VertexBuffer.prototype.getData = function () {
            return this._buffer.getData();
        };
        /**
         * Gets underlying native buffer
         * @returns underlying native buffer
         */
        VertexBuffer.prototype.getBuffer = function () {
            return this._buffer.getBuffer();
        };
        /**
         * Gets the stride in float32 units (i.e. byte stride / 4).
         * May not be an integer if the byte stride is not divisible by 4.
         * DEPRECATED. Use byteStride instead.
         * @returns the stride in float32 units
         */
        VertexBuffer.prototype.getStrideSize = function () {
            return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
        };
        /**
         * Returns the offset as a multiple of the type byte length.
         * DEPRECATED. Use byteOffset instead.
         * @returns the offset in bytes
         */
        VertexBuffer.prototype.getOffset = function () {
            return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
        };
        /**
         * Returns the number of components per vertex attribute (integer)
         * @returns the size in float
         */
        VertexBuffer.prototype.getSize = function () {
            return this._size;
        };
        /**
         * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
         * @returns true if this buffer is instanced
         */
        VertexBuffer.prototype.getIsInstanced = function () {
            return this._instanced;
        };
        /**
         * Returns the instancing divisor, zero for non-instanced (integer).
         * @returns a number
         */
        VertexBuffer.prototype.getInstanceDivisor = function () {
            return this._instanceDivisor;
        };
        // Methods
        /**
         * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
         * @param data defines the data to store
         */
        VertexBuffer.prototype.create = function (data) {
            this._buffer.create(data);
        };
        /**
         * Updates the underlying buffer according to the passed numeric array or Float32Array.
         * This function will create a new buffer if the current one is not updatable
         * @param data defines the data to store
         */
        VertexBuffer.prototype.update = function (data) {
            this._buffer.update(data);
        };
        /**
         * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
         * Returns the directly updated WebGLBuffer.
         * @param data the new data
         * @param offset the new offset
         * @param useBytes set to true if the offset is in bytes
         */
        VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
            if (useBytes === void 0) { useBytes = false; }
            this._buffer.updateDirectly(data, offset, undefined, useBytes);
        };
        /**
         * Disposes the VertexBuffer and the underlying WebGLBuffer.
         */
        VertexBuffer.prototype.dispose = function () {
            if (this._ownsBuffer) {
                this._buffer.dispose();
            }
        };
        /**
         * Enumerates each value of this vertex buffer as numbers.
         * @param count the number of values to enumerate
         * @param callback the callback function called for each value
         */
        VertexBuffer.prototype.forEach = function (count, callback) {
            VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
        };
        /**
         * Deduces the stride given a kind.
         * @param kind The kind string to deduce
         * @returns The deduced stride
         */
        VertexBuffer.DeduceStride = function (kind) {
            switch (kind) {
                case VertexBuffer.UVKind:
                case VertexBuffer.UV2Kind:
                case VertexBuffer.UV3Kind:
                case VertexBuffer.UV4Kind:
                case VertexBuffer.UV5Kind:
                case VertexBuffer.UV6Kind:
                    return 2;
                case VertexBuffer.NormalKind:
                case VertexBuffer.PositionKind:
                    return 3;
                case VertexBuffer.ColorKind:
                case VertexBuffer.MatricesIndicesKind:
                case VertexBuffer.MatricesIndicesExtraKind:
                case VertexBuffer.MatricesWeightsKind:
                case VertexBuffer.MatricesWeightsExtraKind:
                case VertexBuffer.TangentKind:
                    return 4;
                default:
                    throw new Error("Invalid kind '" + kind + "'");
            }
        };
        /**
         * Gets the byte length of the given type.
         * @param type the type
         * @returns the number of bytes
         */
        VertexBuffer.GetTypeByteLength = function (type) {
            switch (type) {
                case VertexBuffer.BYTE:
                case VertexBuffer.UNSIGNED_BYTE:
                    return 1;
                case VertexBuffer.SHORT:
                case VertexBuffer.UNSIGNED_SHORT:
                    return 2;
                case VertexBuffer.INT:
                case VertexBuffer.FLOAT:
                    return 4;
                default:
                    throw new Error("Invalid type '" + type + "'");
            }
        };
        /**
         * Enumerates each value of the given parameters as numbers.
         * @param data the data to enumerate
         * @param byteOffset the byte offset of the data
         * @param byteStride the byte stride of the data
         * @param componentCount the number of components per element
         * @param componentType the type of the component
         * @param count the total number of components
         * @param normalized whether the data is normalized
         * @param callback the callback function called for each value
         */
        VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
            if (data instanceof Array) {
                var offset = byteOffset / 4;
                var stride = byteStride / 4;
                for (var index = 0; index < count; index += componentCount) {
                    for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
                        callback(data[offset + componentIndex], index + componentIndex);
                    }
                    offset += stride;
                }
            }
            else {
                var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
                var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
                for (var index = 0; index < count; index += componentCount) {
                    var componentByteOffset = byteOffset;
                    for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
                        var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
                        callback(value, index + componentIndex);
                        componentByteOffset += componentByteLength;
                    }
                    byteOffset += byteStride;
                }
            }
        };
        VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
            switch (type) {
                case VertexBuffer.BYTE: {
                    var value = dataView.getInt8(byteOffset);
                    if (normalized) {
                        value = Math.max(value / 127, -1);
                    }
                    return value;
                }
                case VertexBuffer.UNSIGNED_BYTE: {
                    var value = dataView.getUint8(byteOffset);
                    if (normalized) {
                        value = value / 255;
                    }
                    return value;
                }
                case VertexBuffer.SHORT: {
                    var value = dataView.getInt16(byteOffset, true);
                    if (normalized) {
                        value = Math.max(value / 16383, -1);
                    }
                    return value;
                }
                case VertexBuffer.UNSIGNED_SHORT: {
                    var value = dataView.getUint16(byteOffset, true);
                    if (normalized) {
                        value = value / 65535;
                    }
                    return value;
                }
                case VertexBuffer.FLOAT: {
                    return dataView.getFloat32(byteOffset, true);
                }
                default: {
                    throw new Error("Invalid component type " + type);
                }
            }
        };
        /**
         * The byte type.
         */
        VertexBuffer.BYTE = 5120;
        /**
         * The unsigned byte type.
         */
        VertexBuffer.UNSIGNED_BYTE = 5121;
        /**
         * The short type.
         */
        VertexBuffer.SHORT = 5122;
        /**
         * The unsigned short type.
         */
        VertexBuffer.UNSIGNED_SHORT = 5123;
        /**
         * The integer type.
         */
        VertexBuffer.INT = 5124;
        /**
         * The unsigned integer type.
         */
        VertexBuffer.UNSIGNED_INT = 5125;
        /**
         * The float type.
         */
        VertexBuffer.FLOAT = 5126;
        // Enums
        /**
         * Positions
         */
        VertexBuffer.PositionKind = "position";
        /**
         * Normals
         */
        VertexBuffer.NormalKind = "normal";
        /**
         * Tangents
         */
        VertexBuffer.TangentKind = "tangent";
        /**
         * Texture coordinates
         */
        VertexBuffer.UVKind = "uv";
        /**
         * Texture coordinates 2
         */
        VertexBuffer.UV2Kind = "uv2";
        /**
         * Texture coordinates 3
         */
        VertexBuffer.UV3Kind = "uv3";
        /**
         * Texture coordinates 4
         */
        VertexBuffer.UV4Kind = "uv4";
        /**
         * Texture coordinates 5
         */
        VertexBuffer.UV5Kind = "uv5";
        /**
         * Texture coordinates 6
         */
        VertexBuffer.UV6Kind = "uv6";
        /**
         * Colors
         */
        VertexBuffer.ColorKind = "color";
        /**
         * Matrix indices (for bones)
         */
        VertexBuffer.MatricesIndicesKind = "matricesIndices";
        /**
         * Matrix weights (for bones)
         */
        VertexBuffer.MatricesWeightsKind = "matricesWeights";
        /**
         * Additional matrix indices (for bones)
         */
        VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
        /**
         * Additional matrix weights (for bones)
         */
        VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
        return VertexBuffer;
    }());
    BABYLON.VertexBuffer = VertexBuffer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vertexBuffer.js.map



//# sourceMappingURL=babylon.internalTextureLoader.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Internal class used by the engine to get list of InternalTexture already bound to the GL context
     */
    var DummyInternalTextureTracker = /** @class */ (function () {
        function DummyInternalTextureTracker() {
            /**
             * Gets or set the previous tracker in the list
             */
            this.previous = null;
            /**
             * Gets or set the next tracker in the list
             */
            this.next = null;
        }
        return DummyInternalTextureTracker;
    }());
    BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.internalTextureTracker.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store data associated with WebGL texture data for the engine
     * This class should not be used directly
     */
    var InternalTexture = /** @class */ (function () {
        /**
         * Creates a new InternalTexture
         * @param engine defines the engine to use
         * @param dataSource defines the type of data that will be used
         */
        function InternalTexture(engine, dataSource) {
            /**
             * Observable called when the texture is loaded
             */
            this.onLoadedObservable = new BABYLON.Observable();
            /**
             * Gets or set the previous tracker in the list
             */
            this.previous = null;
            /**
             * Gets or set the next tracker in the list
             */
            this.next = null;
            // Private
            /** @hidden */
            this._initialSlot = -1;
            /** @hidden */
            this._designatedSlot = -1;
            /** @hidden */
            this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
            /** @hidden */
            this._comparisonFunction = 0;
            /** @hidden */
            this._sphericalPolynomial = null;
            /** @hidden */
            this._lodGenerationScale = 0;
            /** @hidden */
            this._lodGenerationOffset = 0;
            /** @hidden */
            this._isRGBD = false;
            /** @hidden */
            this._references = 1;
            this._engine = engine;
            this._dataSource = dataSource;
            this._webGLTexture = engine._createTexture();
        }
        /**
         * Gets the Engine the texture belongs to.
         * @returns The babylon engine
         */
        InternalTexture.prototype.getEngine = function () {
            return this._engine;
        };
        Object.defineProperty(InternalTexture.prototype, "dataSource", {
            /**
             * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
             */
            get: function () {
                return this._dataSource;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Increments the number of references (ie. the number of Texture that point to it)
         */
        InternalTexture.prototype.incrementReferences = function () {
            this._references++;
        };
        /**
         * Change the size of the texture (not the size of the content)
         * @param width defines the new width
         * @param height defines the new height
         * @param depth defines the new depth (1 by default)
         */
        InternalTexture.prototype.updateSize = function (width, height, depth) {
            if (depth === void 0) { depth = 1; }
            this.width = width;
            this.height = height;
            this.depth = depth;
            this.baseWidth = width;
            this.baseHeight = height;
            this.baseDepth = depth;
            this._size = width * height * depth;
        };
        /** @hidden */
        InternalTexture.prototype._rebuild = function () {
            var _this = this;
            var proxy;
            this.isReady = false;
            this._cachedCoordinatesMode = null;
            this._cachedWrapU = null;
            this._cachedWrapV = null;
            this._cachedAnisotropicFilteringLevel = null;
            switch (this._dataSource) {
                case InternalTexture.DATASOURCE_TEMP:
                    return;
                case InternalTexture.DATASOURCE_URL:
                    proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
                        _this.isReady = true;
                    }, null, this._buffer, undefined, this.format);
                    proxy._swapAndDie(this);
                    return;
                case InternalTexture.DATASOURCE_RAW:
                    proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
                    proxy._swapAndDie(this);
                    this.isReady = true;
                    return;
                case InternalTexture.DATASOURCE_RAW3D:
                    proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
                    proxy._swapAndDie(this);
                    this.isReady = true;
                    return;
                case InternalTexture.DATASOURCE_DYNAMIC:
                    proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
                    proxy._swapAndDie(this);
                    // The engine will make sure to update content so no need to flag it as isReady = true
                    return;
                case InternalTexture.DATASOURCE_RENDERTARGET:
                    var options = new BABYLON.RenderTargetCreationOptions();
                    options.generateDepthBuffer = this._generateDepthBuffer;
                    options.generateMipMaps = this.generateMipMaps;
                    options.generateStencilBuffer = this._generateStencilBuffer;
                    options.samplingMode = this.samplingMode;
                    options.type = this.type;
                    if (this.isCube) {
                        proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
                    }
                    else {
                        var size = {
                            width: this.width,
                            height: this.height
                        };
                        proxy = this._engine.createRenderTargetTexture(size, options);
                    }
                    proxy._swapAndDie(this);
                    this.isReady = true;
                    return;
                case InternalTexture.DATASOURCE_DEPTHTEXTURE:
                    var depthTextureOptions = {
                        bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
                        comparisonFunction: this._comparisonFunction,
                        generateStencil: this._generateStencilBuffer,
                        isCube: this.isCube
                    };
                    proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
                    proxy._swapAndDie(this);
                    this.isReady = true;
                    return;
                case InternalTexture.DATASOURCE_CUBE:
                    proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
                        _this.isReady = true;
                    }, null, this.format, this._extension);
                    proxy._swapAndDie(this);
                    return;
                case InternalTexture.DATASOURCE_CUBERAW:
                    proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
                    proxy._swapAndDie(this);
                    this.isReady = true;
                    return;
                case InternalTexture.DATASOURCE_CUBERAW_RGBD:
                    proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
                    BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
                        _this.isReady = true;
                    });
                    proxy._swapAndDie(this);
                    return;
                case InternalTexture.DATASOURCE_CUBEPREFILTERED:
                    proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
                        if (proxy) {
                            proxy._swapAndDie(_this);
                        }
                        _this.isReady = true;
                    }, null, this.format, this._extension);
                    proxy._sphericalPolynomial = this._sphericalPolynomial;
                    return;
            }
        };
        /** @hidden */
        InternalTexture.prototype._swapAndDie = function (target) {
            target._webGLTexture = this._webGLTexture;
            if (this._framebuffer) {
                target._framebuffer = this._framebuffer;
            }
            if (this._depthStencilBuffer) {
                target._depthStencilBuffer = this._depthStencilBuffer;
            }
            if (this._lodTextureHigh) {
                if (target._lodTextureHigh) {
                    target._lodTextureHigh.dispose();
                }
                target._lodTextureHigh = this._lodTextureHigh;
            }
            if (this._lodTextureMid) {
                if (target._lodTextureMid) {
                    target._lodTextureMid.dispose();
                }
                target._lodTextureMid = this._lodTextureMid;
            }
            if (this._lodTextureLow) {
                if (target._lodTextureLow) {
                    target._lodTextureLow.dispose();
                }
                target._lodTextureLow = this._lodTextureLow;
            }
            var cache = this._engine.getLoadedTexturesCache();
            var index = cache.indexOf(this);
            if (index !== -1) {
                cache.splice(index, 1);
            }
        };
        /**
         * Dispose the current allocated resources
         */
        InternalTexture.prototype.dispose = function () {
            if (!this._webGLTexture) {
                return;
            }
            this._references--;
            if (this._references === 0) {
                this._engine._releaseTexture(this);
                this._webGLTexture = null;
                this.previous = null;
                this.next = null;
            }
        };
        /**
         * The source of the texture data is unknown
         */
        InternalTexture.DATASOURCE_UNKNOWN = 0;
        /**
         * Texture data comes from an URL
         */
        InternalTexture.DATASOURCE_URL = 1;
        /**
         * Texture data is only used for temporary storage
         */
        InternalTexture.DATASOURCE_TEMP = 2;
        /**
         * Texture data comes from raw data (ArrayBuffer)
         */
        InternalTexture.DATASOURCE_RAW = 3;
        /**
         * Texture content is dynamic (video or dynamic texture)
         */
        InternalTexture.DATASOURCE_DYNAMIC = 4;
        /**
         * Texture content is generated by rendering to it
         */
        InternalTexture.DATASOURCE_RENDERTARGET = 5;
        /**
         * Texture content is part of a multi render target process
         */
        InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
        /**
         * Texture data comes from a cube data file
         */
        InternalTexture.DATASOURCE_CUBE = 7;
        /**
         * Texture data comes from a raw cube data
         */
        InternalTexture.DATASOURCE_CUBERAW = 8;
        /**
         * Texture data come from a prefiltered cube data file
         */
        InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
        /**
         * Texture content is raw 3D data
         */
        InternalTexture.DATASOURCE_RAW3D = 10;
        /**
         * Texture content is a depth texture
         */
        InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
        /**
         * Texture data comes from a raw cube data encoded with RGBD
         */
        InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
        return InternalTexture;
    }());
    BABYLON.InternalTexture = InternalTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.internalTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Base class of all the textures in babylon.
     * It groups all the common properties the materials, post process, lights... might need
     * in order to make a correct use of the texture.
     */
    var BaseTexture = /** @class */ (function () {
        /**
         * Instantiates a new BaseTexture.
         * Base class of all the textures in babylon.
         * It groups all the common properties the materials, post process, lights... might need
         * in order to make a correct use of the texture.
         * @param scene Define the scene the texture blongs to
         */
        function BaseTexture(scene) {
            this._hasAlpha = false;
            /**
             * Defines if the alpha value should be determined via the rgb values.
             * If true the luminance of the pixel might be used to find the corresponding alpha value.
             */
            this.getAlphaFromRGB = false;
            /**
             * Intensity or strength of the texture.
             * It is commonly used by materials to fine tune the intensity of the texture
             */
            this.level = 1;
            /**
             * Define the UV chanel to use starting from 0 and defaulting to 0.
             * This is part of the texture as textures usually maps to one uv set.
             */
            this.coordinatesIndex = 0;
            this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
            /**
            * | Value | Type               | Description |
            * | ----- | ------------------ | ----------- |
            * | 0     | CLAMP_ADDRESSMODE  |             |
            * | 1     | WRAP_ADDRESSMODE   |             |
            * | 2     | MIRROR_ADDRESSMODE |             |
            */
            this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            /**
            * | Value | Type               | Description |
            * | ----- | ------------------ | ----------- |
            * | 0     | CLAMP_ADDRESSMODE  |             |
            * | 1     | WRAP_ADDRESSMODE   |             |
            * | 2     | MIRROR_ADDRESSMODE |             |
            */
            this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            /**
            * | Value | Type               | Description |
            * | ----- | ------------------ | ----------- |
            * | 0     | CLAMP_ADDRESSMODE  |             |
            * | 1     | WRAP_ADDRESSMODE   |             |
            * | 2     | MIRROR_ADDRESSMODE |             |
            */
            this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
            /**
             * With compliant hardware and browser (supporting anisotropic filtering)
             * this defines the level of anisotropic filtering in the texture.
             * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
             */
            this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
            /**
             * Define if the texture is a cube texture or if false a 2d texture.
             */
            this.isCube = false;
            /**
             * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
             */
            this.is3D = false;
            /**
             * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
             * HDR texture are usually stored in linear space.
             * This only impacts the PBR and Background materials
             */
            this.gammaSpace = true;
            /**
             * Is Z inverted in the texture (useful in a cube texture).
             */
            this.invertZ = false;
            /**
             * @hidden
             */
            this.lodLevelInAlpha = false;
            /**
             * Define if the texture is a render target.
             */
            this.isRenderTarget = false;
            /**
             * Define the list of animation attached to the texture.
             */
            this.animations = new Array();
            /**
            * An event triggered when the texture is disposed.
            */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
             * Define the current state of the loading sequence when in delayed load mode.
             */
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this._cachedSize = BABYLON.Size.Zero();
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            if (this._scene) {
                this._scene.textures.push(this);
                this._scene.onNewTextureAddedObservable.notifyObservers(this);
            }
            this._uid = null;
        }
        Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
            get: function () {
                return this._hasAlpha;
            },
            /**
             * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
             */
            set: function (value) {
                if (this._hasAlpha === value) {
                    return;
                }
                this._hasAlpha = value;
                if (this._scene) {
                    this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
            get: function () {
                return this._coordinatesMode;
            },
            /**
            * How a texture is mapped.
            *
            * | Value | Type                                | Description |
            * | ----- | ----------------------------------- | ----------- |
            * | 0     | EXPLICIT_MODE                       |             |
            * | 1     | SPHERICAL_MODE                      |             |
            * | 2     | PLANAR_MODE                         |             |
            * | 3     | CUBIC_MODE                          |             |
            * | 4     | PROJECTION_MODE                     |             |
            * | 5     | SKYBOX_MODE                         |             |
            * | 6     | INVCUBIC_MODE                       |             |
            * | 7     | EQUIRECTANGULAR_MODE                |             |
            * | 8     | FIXED_EQUIRECTANGULAR_MODE          |             |
            * | 9     | FIXED_EQUIRECTANGULAR_MIRRORED_MODE |             |
            */
            set: function (value) {
                if (this._coordinatesMode === value) {
                    return;
                }
                this._coordinatesMode = value;
                if (this._scene) {
                    this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "isRGBD", {
            /**
             * Gets whether or not the texture contains RGBD data.
             */
            get: function () {
                return this._texture != null && this._texture._isRGBD;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
            /**
             * With prefiltered texture, defined the offset used during the prefiltering steps.
             */
            get: function () {
                if (this._texture) {
                    return this._texture._lodGenerationOffset;
                }
                return 0.0;
            },
            set: function (value) {
                if (this._texture) {
                    this._texture._lodGenerationOffset = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
            /**
             * With prefiltered texture, defined the scale used during the prefiltering steps.
             */
            get: function () {
                if (this._texture) {
                    return this._texture._lodGenerationScale;
                }
                return 0.0;
            },
            set: function (value) {
                if (this._texture) {
                    this._texture._lodGenerationScale = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "uid", {
            /**
             * Define the unique id of the texture in the scene.
             */
            get: function () {
                if (!this._uid) {
                    this._uid = BABYLON.Tools.RandomId();
                }
                return this._uid;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Return a string representation of the texture.
         * @returns the texture as a string
         */
        BaseTexture.prototype.toString = function () {
            return this.name;
        };
        /**
         * Get the class name of the texture.
         * @returns "BaseTexture"
         */
        BaseTexture.prototype.getClassName = function () {
            return "BaseTexture";
        };
        Object.defineProperty(BaseTexture.prototype, "onDispose", {
            /**
             * Callback triggered when the texture has been disposed.
             * Kept for back compatibility, you can use the onDisposeObservable instead.
             */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "isBlocking", {
            /**
             * Define if the texture is preventinga material to render or not.
             * If not and the texture is not ready, the engine will use a default black texture instead.
             */
            get: function () {
                return true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get the scene the texture belongs to.
         * @returns the scene or null if undefined
         */
        BaseTexture.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Get the texture transform matrix used to offset tile the texture for istance.
         * @returns the transformation matrix
         */
        BaseTexture.prototype.getTextureMatrix = function () {
            return BABYLON.Matrix.IdentityReadOnly;
        };
        /**
         * Get the texture reflection matrix used to rotate/transform the reflection.
         * @returns the reflection matrix
         */
        BaseTexture.prototype.getReflectionTextureMatrix = function () {
            return BABYLON.Matrix.IdentityReadOnly;
        };
        /**
         * Get the underlying lower level texture from Babylon.
         * @returns the insternal texture
         */
        BaseTexture.prototype.getInternalTexture = function () {
            return this._texture;
        };
        /**
         * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
         * @returns true if ready or not blocking
         */
        BaseTexture.prototype.isReadyOrNotBlocking = function () {
            return !this.isBlocking || this.isReady();
        };
        /**
         * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
         * @returns true if fully ready
         */
        BaseTexture.prototype.isReady = function () {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                this.delayLoad();
                return false;
            }
            if (this._texture) {
                return this._texture.isReady;
            }
            return false;
        };
        /**
         * Get the size of the texture.
         * @returns the texture size.
         */
        BaseTexture.prototype.getSize = function () {
            if (this._texture) {
                if (this._texture.width) {
                    this._cachedSize.width = this._texture.width;
                    this._cachedSize.height = this._texture.height;
                    return this._cachedSize;
                }
                if (this._texture._size) {
                    this._cachedSize.width = this._texture._size;
                    this._cachedSize.height = this._texture._size;
                    return this._cachedSize;
                }
            }
            return this._cachedSize;
        };
        /**
         * Get the base size of the texture.
         * It can be different from the size if the texture has been resized for POT for instance
         * @returns the base size
         */
        BaseTexture.prototype.getBaseSize = function () {
            if (!this.isReady() || !this._texture) {
                return BABYLON.Size.Zero();
            }
            if (this._texture._size) {
                return new BABYLON.Size(this._texture._size, this._texture._size);
            }
            return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
        };
        /**
         * Scales the texture if is `canRescale()`
         * @param ratio the resize factor we want to use to rescale
         */
        BaseTexture.prototype.scale = function (ratio) {
        };
        Object.defineProperty(BaseTexture.prototype, "canRescale", {
            /**
             * Get if the texture can rescale.
             */
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
            if (!this._scene) {
                return null;
            }
            var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
            for (var index = 0; index < texturesCache.length; index++) {
                var texturesCacheEntry = texturesCache[index];
                if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
                    if (!sampling || sampling === texturesCacheEntry.samplingMode) {
                        texturesCacheEntry.incrementReferences();
                        return texturesCacheEntry;
                    }
                }
            }
            return null;
        };
        /** @hidden */
        BaseTexture.prototype._rebuild = function () {
        };
        /**
         * Triggers the load sequence in delayed load mode.
         */
        BaseTexture.prototype.delayLoad = function () {
        };
        /**
         * Clones the texture.
         * @returns the cloned texture
         */
        BaseTexture.prototype.clone = function () {
            return null;
        };
        Object.defineProperty(BaseTexture.prototype, "textureType", {
            /**
             * Get the texture underlying type (INT, FLOAT...)
             */
            get: function () {
                if (!this._texture) {
                    return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                }
                return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "textureFormat", {
            /**
             * Get the texture underlying format (RGB, RGBA...)
             */
            get: function () {
                if (!this._texture) {
                    return BABYLON.Engine.TEXTUREFORMAT_RGBA;
                }
                return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
         * This will returns an RGBA array buffer containing either in values (0-255) or
         * float values (0-1) depending of the underlying buffer type.
         * @param faceIndex defines the face of the texture to read (in case of cube texture)
         * @param level defines the LOD level of the texture to read (in case of Mip Maps)
         * @param buffer defines a user defined buffer to fill with data (can be null)
         * @returns The Array buffer containing the pixels data.
         */
        BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (level === void 0) { level = 0; }
            if (buffer === void 0) { buffer = null; }
            if (!this._texture) {
                return null;
            }
            var size = this.getSize();
            var width = size.width;
            var height = size.height;
            var scene = this.getScene();
            if (!scene) {
                return null;
            }
            var engine = scene.getEngine();
            if (level != 0) {
                width = width / Math.pow(2, level);
                height = height / Math.pow(2, level);
                width = Math.round(width);
                height = Math.round(height);
            }
            if (this._texture.isCube) {
                return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
            }
            return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
        };
        /**
         * Release and destroy the underlying lower level texture aka internalTexture.
         */
        BaseTexture.prototype.releaseInternalTexture = function () {
            if (this._texture) {
                this._texture.dispose();
                this._texture = null;
            }
        };
        Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
            /**
             * Get the polynomial representation of the texture data.
             * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
             * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
             */
            get: function () {
                if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
                    return null;
                }
                if (!this._texture._sphericalPolynomial) {
                    this._texture._sphericalPolynomial =
                        BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
                }
                return this._texture._sphericalPolynomial;
            },
            set: function (value) {
                if (this._texture) {
                    this._texture._sphericalPolynomial = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
            /** @hidden */
            get: function () {
                if (this._texture) {
                    return this._texture._lodTextureHigh;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
            /** @hidden */
            get: function () {
                if (this._texture) {
                    return this._texture._lodTextureMid;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
            /** @hidden */
            get: function () {
                if (this._texture) {
                    return this._texture._lodTextureLow;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Dispose the texture and release its associated resources.
         */
        BaseTexture.prototype.dispose = function () {
            if (!this._scene) {
                return;
            }
            // Animations
            this._scene.stopAnimation(this);
            // Remove from scene
            this._scene._removePendingData(this);
            var index = this._scene.textures.indexOf(this);
            if (index >= 0) {
                this._scene.textures.splice(index, 1);
            }
            this._scene.onTextureRemovedObservable.notifyObservers(this);
            if (this._texture === undefined) {
                return;
            }
            // Release
            this.releaseInternalTexture();
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        /**
         * Serialize the texture into a JSON representation that can be parsed later on.
         * @returns the JSON representation of the texture
         */
        BaseTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            return serializationObject;
        };
        /**
         * Helper function to be called back once a list of texture contains only ready textures.
         * @param textures Define the list of textures to wait for
         * @param callback Define the callback triggered once the entire list will be ready
         */
        BaseTexture.WhenAllReady = function (textures, callback) {
            var numRemaining = textures.length;
            if (numRemaining === 0) {
                callback();
                return;
            }
            var _loop_1 = function () {
                texture = textures[i];
                if (texture.isReady()) {
                    if (--numRemaining === 0) {
                        callback();
                    }
                }
                else {
                    onLoadObservable = texture.onLoadObservable;
                    var onLoadCallback_1 = function () {
                        onLoadObservable.removeCallback(onLoadCallback_1);
                        if (--numRemaining === 0) {
                            callback();
                        }
                    };
                    onLoadObservable.add(onLoadCallback_1);
                }
            };
            var texture, onLoadObservable;
            for (var i = 0; i < textures.length; i++) {
                _loop_1();
            }
        };
        /**
         * Default anisotropic filtering level for the application.
         * It is set to 4 as a good tradeoff between perf and quality.
         */
        BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "name", void 0);
        __decorate([
            BABYLON.serialize("hasAlpha")
        ], BaseTexture.prototype, "_hasAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "level", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "coordinatesIndex", void 0);
        __decorate([
            BABYLON.serialize("coordinatesMode")
        ], BaseTexture.prototype, "_coordinatesMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "wrapU", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "wrapV", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "wrapR", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "isCube", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "is3D", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "gammaSpace", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "invertZ", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "lodGenerationOffset", null);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "lodGenerationScale", null);
        __decorate([
            BABYLON.serialize()
        ], BaseTexture.prototype, "isRenderTarget", void 0);
        return BaseTexture;
    }());
    BABYLON.BaseTexture = BaseTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.baseTexture.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
     * @see http://doc.babylonjs.com/babylon101/materials#texture
     */
    var Texture = /** @class */ (function (_super) {
        __extends(Texture, _super);
        /**
         * Instantiates a new texture.
         * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
         * @see http://doc.babylonjs.com/babylon101/materials#texture
         * @param url define the url of the picture to load as a texture
         * @param scene define the scene the texture will belong to
         * @param noMipmap define if the texture will require mip maps or not
         * @param invertY define if the texture needs to be inverted on the y axis during loading
         * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
         * @param onLoad define a callback triggered when the texture has been loaded
         * @param onError define a callback triggered when an error occurred during the loading session
         * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
         * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
         * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
         */
        function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
            if (noMipmap === void 0) { noMipmap = false; }
            if (invertY === void 0) { invertY = true; }
            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (buffer === void 0) { buffer = null; }
            if (deleteBuffer === void 0) { deleteBuffer = false; }
            var _this = _super.call(this, scene) || this;
            /**
             * Define an offset on the texture to offset the u coordinates of the UVs
             * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
             */
            _this.uOffset = 0;
            /**
             * Define an offset on the texture to offset the v coordinates of the UVs
             * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
             */
            _this.vOffset = 0;
            /**
             * Define an offset on the texture to scale the u coordinates of the UVs
             * @see http://doc.babylonjs.com/how_to/more_materials#tiling
             */
            _this.uScale = 1.0;
            /**
             * Define an offset on the texture to scale the v coordinates of the UVs
             * @see http://doc.babylonjs.com/how_to/more_materials#tiling
             */
            _this.vScale = 1.0;
            /**
             * Define an offset on the texture to rotate around the u coordinates of the UVs
             * @see http://doc.babylonjs.com/how_to/more_materials
             */
            _this.uAng = 0;
            /**
             * Define an offset on the texture to rotate around the v coordinates of the UVs
             * @see http://doc.babylonjs.com/how_to/more_materials
             */
            _this.vAng = 0;
            /**
             * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
             * @see http://doc.babylonjs.com/how_to/more_materials
             */
            _this.wAng = 0;
            /**
             * Defines the center of rotation (U)
             */
            _this.uRotationCenter = 0.5;
            /**
             * Defines the center of rotation (V)
             */
            _this.vRotationCenter = 0.5;
            /**
             * Defines the center of rotation (W)
             */
            _this.wRotationCenter = 0.5;
            /**
             * Observable triggered once the texture has been loaded.
             */
            _this.onLoadObservable = new BABYLON.Observable();
            _this._isBlocking = true;
            _this.name = url || "";
            _this.url = url;
            _this._noMipmap = noMipmap;
            _this._invertY = invertY;
            _this._samplingMode = samplingMode;
            _this._buffer = buffer;
            _this._deleteBuffer = deleteBuffer;
            if (format) {
                _this._format = format;
            }
            scene = _this.getScene();
            if (!scene) {
                return _this;
            }
            scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
            var load = function () {
                if (_this.onLoadObservable.hasObservers()) {
                    _this.onLoadObservable.notifyObservers(_this);
                }
                if (onLoad) {
                    onLoad();
                }
                if (!_this.isBlocking && scene) {
                    scene.resetCachedMaterial();
                }
            };
            if (!_this.url) {
                _this._delayedOnLoad = load;
                _this._delayedOnError = onError;
                return _this;
            }
            _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
            if (!_this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
                    if (deleteBuffer) {
                        delete _this._buffer;
                    }
                }
                else {
                    _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                    _this._delayedOnLoad = load;
                    _this._delayedOnError = onError;
                }
            }
            else {
                if (_this._texture.isReady) {
                    BABYLON.Tools.SetImmediate(function () { return load(); });
                }
                else {
                    _this._texture.onLoadedObservable.add(load);
                }
            }
            return _this;
        }
        Object.defineProperty(Texture.prototype, "noMipmap", {
            /**
             * Are mip maps generated for this texture or not.
             */
            get: function () {
                return this._noMipmap;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "isBlocking", {
            get: function () {
                return this._isBlocking;
            },
            /**
             * Is the texture preventing material to render while loading.
             * If false, a default texture will be used instead of the loading one during the preparation step.
             */
            set: function (value) {
                this._isBlocking = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Texture.prototype, "samplingMode", {
            /**
             * Get the current sampling mode associated with the texture.
             */
            get: function () {
                return this._samplingMode;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Update the url (and optional buffer) of this texture if url was null during construction.
         * @param url the url of the texture
         * @param buffer the buffer of the texture (defaults to null)
         */
        Texture.prototype.updateURL = function (url, buffer) {
            if (buffer === void 0) { buffer = null; }
            if (this.url) {
                throw new Error("URL is already set");
            }
            this.url = url;
            this._buffer = buffer;
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
            this.delayLoad();
        };
        /**
         * Finish the loading sequence of a texture flagged as delayed load.
         * @hidden
         */
        Texture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
            if (!this._texture) {
                this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
                if (this._deleteBuffer) {
                    delete this._buffer;
                }
            }
            else {
                if (this._delayedOnLoad) {
                    if (this._texture.isReady) {
                        BABYLON.Tools.SetImmediate(this._delayedOnLoad);
                    }
                    else {
                        this._texture.onLoadedObservable.add(this._delayedOnLoad);
                    }
                }
            }
            this._delayedOnLoad = null;
            this._delayedOnError = null;
        };
        /**
          * Update the sampling mode of the texture.
         * Default is Trilinear mode.
         *
         * | Value | Type               | Description |
         * | ----- | ------------------ | ----------- |
         * | 1     | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR  | Nearest is: mag = nearest, min = nearest, mip = linear |
         * | 2     | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
         * | 3     | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
         * | 4     | NEAREST_NEAREST_MIPNEAREST |             |
         * | 5    | NEAREST_LINEAR_MIPNEAREST |             |
         * | 6    | NEAREST_LINEAR_MIPLINEAR |             |
         * | 7    | NEAREST_LINEAR |             |
         * | 8    | NEAREST_NEAREST |             |
         * | 9   | LINEAR_NEAREST_MIPNEAREST |             |
         * | 10   | LINEAR_NEAREST_MIPLINEAR |             |
         * | 11   | LINEAR_LINEAR |             |
         * | 12   | LINEAR_NEAREST |             |
         *
         *    > _mag_: magnification filter (close to the viewer)
         *    > _min_: minification filter (far from the viewer)
         *    > _mip_: filter used between mip map levels
         *@param samplingMode Define the new sampling mode of the texture
         */
        Texture.prototype.updateSamplingMode = function (samplingMode) {
            if (!this._texture) {
                return;
            }
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            this._samplingMode = samplingMode;
            scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
        };
        Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
            x *= this.uScale;
            y *= this.vScale;
            x -= this.uRotationCenter * this.uScale;
            y -= this.vRotationCenter * this.vScale;
            z -= this.wRotationCenter;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
            t.x += this.uRotationCenter * this.uScale + this.uOffset;
            t.y += this.vRotationCenter * this.vScale + this.vOffset;
            t.z += this.wRotationCenter;
        };
        /**
         * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
         * @returns the transform matrix of the texture.
         */
        Texture.prototype.getTextureMatrix = function () {
            var _this = this;
            if (this.uOffset === this._cachedUOffset &&
                this.vOffset === this._cachedVOffset &&
                this.uScale === this._cachedUScale &&
                this.vScale === this._cachedVScale &&
                this.uAng === this._cachedUAng &&
                this.vAng === this._cachedVAng &&
                this.wAng === this._cachedWAng) {
                return this._cachedTextureMatrix;
            }
            this._cachedUOffset = this.uOffset;
            this._cachedVOffset = this.vOffset;
            this._cachedUScale = this.uScale;
            this._cachedVScale = this.vScale;
            this._cachedUAng = this.uAng;
            this._cachedVAng = this.vAng;
            this._cachedWAng = this.wAng;
            if (!this._cachedTextureMatrix) {
                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
                this._rowGenerationMatrix = new BABYLON.Matrix();
                this._t0 = BABYLON.Vector3.Zero();
                this._t1 = BABYLON.Vector3.Zero();
                this._t2 = BABYLON.Vector3.Zero();
            }
            BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
            this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
            this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
            this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
            this._t1.subtractInPlace(this._t0);
            this._t2.subtractInPlace(this._t0);
            BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
            this._cachedTextureMatrix.m[0] = this._t1.x;
            this._cachedTextureMatrix.m[1] = this._t1.y;
            this._cachedTextureMatrix.m[2] = this._t1.z;
            this._cachedTextureMatrix.m[4] = this._t2.x;
            this._cachedTextureMatrix.m[5] = this._t2.y;
            this._cachedTextureMatrix.m[6] = this._t2.z;
            this._cachedTextureMatrix.m[8] = this._t0.x;
            this._cachedTextureMatrix.m[9] = this._t0.y;
            this._cachedTextureMatrix.m[10] = this._t0.z;
            var scene = this.getScene();
            if (!scene) {
                return this._cachedTextureMatrix;
            }
            scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
                return mat.hasTexture(_this);
            });
            return this._cachedTextureMatrix;
        };
        /**
         * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
         * @returns The reflection texture transform
         */
        Texture.prototype.getReflectionTextureMatrix = function () {
            var _this = this;
            var scene = this.getScene();
            if (!scene) {
                return this._cachedTextureMatrix;
            }
            if (this.uOffset === this._cachedUOffset &&
                this.vOffset === this._cachedVOffset &&
                this.uScale === this._cachedUScale &&
                this.vScale === this._cachedVScale &&
                this.coordinatesMode === this._cachedCoordinatesMode) {
                if (this.coordinatesMode === Texture.PROJECTION_MODE) {
                    if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
                        return this._cachedTextureMatrix;
                    }
                }
                else {
                    return this._cachedTextureMatrix;
                }
            }
            if (!this._cachedTextureMatrix) {
                this._cachedTextureMatrix = BABYLON.Matrix.Zero();
            }
            if (!this._projectionModeMatrix) {
                this._projectionModeMatrix = BABYLON.Matrix.Zero();
            }
            this._cachedUOffset = this.uOffset;
            this._cachedVOffset = this.vOffset;
            this._cachedUScale = this.uScale;
            this._cachedVScale = this.vScale;
            this._cachedCoordinatesMode = this.coordinatesMode;
            switch (this.coordinatesMode) {
                case Texture.PLANAR_MODE:
                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
                    this._cachedTextureMatrix[0] = this.uScale;
                    this._cachedTextureMatrix[5] = this.vScale;
                    this._cachedTextureMatrix[12] = this.uOffset;
                    this._cachedTextureMatrix[13] = this.vOffset;
                    break;
                case Texture.PROJECTION_MODE:
                    BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
                    this._projectionModeMatrix.m[0] = 0.5;
                    this._projectionModeMatrix.m[5] = -0.5;
                    this._projectionModeMatrix.m[10] = 0.0;
                    this._projectionModeMatrix.m[12] = 0.5;
                    this._projectionModeMatrix.m[13] = 0.5;
                    this._projectionModeMatrix.m[14] = 1.0;
                    this._projectionModeMatrix.m[15] = 1.0;
                    var projectionMatrix = scene.getProjectionMatrix();
                    this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
                    projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
                    break;
                default:
                    BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
                    break;
            }
            scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
                return (mat.getActiveTextures().indexOf(_this) !== -1);
            });
            return this._cachedTextureMatrix;
        };
        /**
         * Clones the texture.
         * @returns the cloned texture
         */
        Texture.prototype.clone = function () {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () {
                return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
            }, this);
        };
        /**
         * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
         * @returns The JSON representation of the texture
         */
        Texture.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
                serializationObject.base64String = this._buffer;
                serializationObject.name = serializationObject.name.replace("data:", "");
            }
            serializationObject.invertY = this._invertY;
            serializationObject.samplingMode = this.samplingMode;
            return serializationObject;
        };
        /**
         * Get the current class name of the texture usefull for serialization or dynamic coding.
         * @returns "Texture"
         */
        Texture.prototype.getClassName = function () {
            return "Texture";
        };
        /**
         * Dispose the texture and release its associated resources.
         */
        Texture.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.onLoadObservable.clear();
            this._delayedOnLoad = null;
            this._delayedOnError = null;
        };
        /**
         * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
         * @param parsedTexture Define the JSON representation of the texture
         * @param scene Define the scene the parsed texture should be instantiated in
         * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
         * @returns The parsed texture if successful
         */
        Texture.Parse = function (parsedTexture, scene, rootUrl) {
            if (parsedTexture.customType) {
                var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
                // Update Sampling Mode
                var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
                if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
                    if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
                        parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
                    }
                }
                return parsedCustomTexture;
            }
            if (parsedTexture.isCube) {
                return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
            }
            if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
                return null;
            }
            var texture = BABYLON.SerializationHelper.Parse(function () {
                var generateMipMaps = true;
                if (parsedTexture.noMipmap) {
                    generateMipMaps = false;
                }
                if (parsedTexture.mirrorPlane) {
                    var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
                    mirrorTexture._waitingRenderList = parsedTexture.renderList;
                    mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
                    return mirrorTexture;
                }
                else if (parsedTexture.isRenderTarget) {
                    var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
                    renderTargetTexture._waitingRenderList = parsedTexture.renderList;
                    return renderTargetTexture;
                }
                else {
                    var texture;
                    if (parsedTexture.base64String) {
                        texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
                    }
                    else {
                        var url = rootUrl + parsedTexture.name;
                        if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
                            url = parsedTexture.url;
                        }
                        texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
                    }
                    return texture;
                }
            }, parsedTexture, scene);
            // Update Sampling Mode
            if (parsedTexture.samplingMode) {
                var sampling = parsedTexture.samplingMode;
                if (texture._samplingMode !== sampling) {
                    texture.updateSamplingMode(sampling);
                }
            }
            // Animations
            if (parsedTexture.animations) {
                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
                    var parsedAnimation = parsedTexture.animations[animationIndex];
                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
            }
            return texture;
        };
        /**
         * Creates a texture from its base 64 representation.
         * @param data Define the base64 payload without the data: prefix
         * @param name Define the name of the texture in the scene useful fo caching purpose for instance
         * @param scene Define the scene the texture should belong to
         * @param noMipmap Forces the texture to not create mip map information if true
         * @param invertY define if the texture needs to be inverted on the y axis during loading
         * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
         * @param onLoad define a callback triggered when the texture has been loaded
         * @param onError define a callback triggered when an error occurred during the loading session
         * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
         * @returns the created texture
         */
        Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
            return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
        };
        /**
         * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
         * @param data Define the base64 payload without the data: prefix
         * @param name Define the name of the texture in the scene useful fo caching purpose for instance
         * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
         * @param scene Define the scene the texture should belong to
         * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
         * @param noMipmap Forces the texture to not create mip map information if true
         * @param invertY define if the texture needs to be inverted on the y axis during loading
         * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
         * @param onLoad define a callback triggered when the texture has been loaded
         * @param onError define a callback triggered when an error occurred during the loading session
         * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
         * @returns the created texture
         */
        Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
            if (deleteBuffer === void 0) { deleteBuffer = false; }
            if (noMipmap === void 0) { noMipmap = false; }
            if (invertY === void 0) { invertY = true; }
            if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
            if (name.substr(0, 5) !== "data:") {
                name = "data:" + name;
            }
            return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
        };
        /** nearest is mag = nearest and min = nearest and mip = linear */
        Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
        /** nearest is mag = nearest and min = nearest and mip = linear */
        Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
        /** Bilinear is mag = linear and min = linear and mip = nearest */
        Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
        /** Bilinear is mag = linear and min = linear and mip = nearest */
        Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
        /** Trilinear is mag = linear and min = linear and mip = linear */
        Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
        /** Trilinear is mag = linear and min = linear and mip = linear */
        Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
        /** mag = nearest and min = nearest and mip = nearest */
        Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
        /** mag = nearest and min = linear and mip = nearest */
        Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
        /** mag = nearest and min = linear and mip = linear */
        Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
        /** mag = nearest and min = linear and mip = none */
        Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
        /** mag = nearest and min = nearest and mip = none */
        Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
        /** mag = linear and min = nearest and mip = nearest */
        Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
        /** mag = linear and min = nearest and mip = linear */
        Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
        /** mag = linear and min = linear and mip = none */
        Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
        /** mag = linear and min = nearest and mip = none */
        Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
        /** Explicit coordinates mode */
        Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
        /** Spherical coordinates mode */
        Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
        /** Planar coordinates mode */
        Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
        /** Cubic coordinates mode */
        Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
        /** Projection coordinates mode */
        Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
        /** Inverse Cubic coordinates mode */
        Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
        /** Inverse Cubic coordinates mode */
        Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
        /** Equirectangular coordinates mode */
        Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
        /** Equirectangular Fixed coordinates mode */
        Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
        /** Equirectangular Fixed Mirrored coordinates mode */
        Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
        /** Texture is not repeating outside of 0..1 UVs */
        Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
        /** Texture is repeating outside of 0..1 UVs */
        Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
        /** Texture is repeating and mirrored */
        Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
        /**
         * Gets or sets a boolean which defines if the texture url must be build from the serialized URL instead of just using the name and loading them side by side with the scene file
         */
        Texture.UseSerializedUrlIfAny = false;
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "url", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uScale", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vScale", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uAng", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vAng", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "wAng", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "uRotationCenter", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "vRotationCenter", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "wRotationCenter", void 0);
        __decorate([
            BABYLON.serialize()
        ], Texture.prototype, "isBlocking", null);
        return Texture;
    }(BABYLON.BaseTexture));
    BABYLON.Texture = Texture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.texture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     **/
    var _CreationDataStorage = /** @class */ (function () {
        function _CreationDataStorage() {
        }
        return _CreationDataStorage;
    }());
    BABYLON._CreationDataStorage = _CreationDataStorage;
    /**
     * @hidden
     **/
    var _InstanceDataStorage = /** @class */ (function () {
        function _InstanceDataStorage() {
            this.visibleInstances = {};
            this.renderIdForInstances = new Array();
            this.batchCache = new _InstancesBatch();
            this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
        }
        return _InstanceDataStorage;
    }());
    /**
     * @hidden
     **/
    var _InstancesBatch = /** @class */ (function () {
        function _InstancesBatch() {
            this.mustReturn = false;
            this.visibleInstances = new Array();
            this.renderSelf = new Array();
        }
        return _InstancesBatch;
    }());
    BABYLON._InstancesBatch = _InstancesBatch;
    /**
     * Class used to represent renderable models
     */
    var Mesh = /** @class */ (function (_super) {
        __extends(Mesh, _super);
        /**
         * @constructor
         * @param name The value used by scene.getMeshByName() to do a lookup.
         * @param scene The scene to add this mesh to.
         * @param parent The parent of this mesh, if it has one
         * @param source An optional Mesh from which geometry is shared, cloned.
         * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
         *                  When false, achieved by calling a clone(), also passing False.
         *                  This will make creation of children, recursive.
         * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
         */
        function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
            if (scene === void 0) { scene = null; }
            if (parent === void 0) { parent = null; }
            if (source === void 0) { source = null; }
            if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
            var _this = _super.call(this, name, scene) || this;
            // Members
            /**
             * Gets the delay loading state of the mesh (when delay loading is turned on)
             * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
             */
            _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            /**
             * Gets the list of instances created from this mesh
             * @see http://doc.babylonjs.com/how_to/how_to_use_instances
             */
            _this.instances = new Array();
            _this._LODLevels = new Array();
            /** @hidden */
            _this._instanceDataStorage = new _InstanceDataStorage();
            // Use by builder only to know what orientation were the mesh build in.
            /** @hidden */
            _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
            /**
             * Use this property to change the original side orientation defined at construction time
             */
            _this.overrideMaterialSideOrientation = null;
            _this._areNormalsFrozen = false; // Will be used by ribbons mainly
            // Will be used to save a source mesh reference, If any
            _this._source = null;
            scene = _this.getScene();
            if (source) {
                // Geometry
                if (source._geometry) {
                    source._geometry.applyToMesh(_this);
                }
                // Deep copy
                BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
                    "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
                    "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
                ], ["_poseMatrix"]);
                // Source mesh
                _this._source = source;
                // Construction Params
                // Clone parameters allowing mesh to be updated in case of parametric shapes.
                _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
                _this._creationDataStorage = source._creationDataStorage;
                // Animation ranges
                if (_this._source._ranges) {
                    var ranges = _this._source._ranges;
                    for (var name in ranges) {
                        if (!ranges.hasOwnProperty(name)) {
                            continue;
                        }
                        if (!ranges[name]) {
                            continue;
                        }
                        _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
                    }
                }
                // Metadata
                if (source.metadata && source.metadata.clone) {
                    _this.metadata = source.metadata.clone();
                }
                else {
                    _this.metadata = source.metadata;
                }
                // Tags
                if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
                    BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
                }
                // Parent
                _this.parent = source.parent;
                // Pivot
                _this.setPivotMatrix(source.getPivotMatrix());
                _this.id = name + "." + source.id;
                // Material
                _this.material = source.material;
                var index;
                if (!doNotCloneChildren) {
                    // Children
                    var directDescendants = source.getDescendants(true);
                    for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
                        var child = directDescendants[index_1];
                        if (child.clone) {
                            child.clone(name + "." + child.name, _this);
                        }
                    }
                }
                // Physics clone
                var physicsEngine = _this.getScene().getPhysicsEngine();
                if (clonePhysicsImpostor && physicsEngine) {
                    var impostor = physicsEngine.getImpostorForPhysicsObject(source);
                    if (impostor) {
                        _this.physicsImpostor = impostor.clone(_this);
                    }
                }
                // Particles
                for (index = 0; index < scene.particleSystems.length; index++) {
                    var system = scene.particleSystems[index];
                    if (system.emitter === source) {
                        system.clone(system.name, _this);
                    }
                }
                _this.refreshBoundingInfo();
                _this.computeWorldMatrix(true);
            }
            // Parent
            if (parent !== null) {
                _this.parent = parent;
            }
            return _this;
        }
        Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
            /**
             * An event triggered before rendering the mesh
             */
            get: function () {
                if (!this._onBeforeRenderObservable) {
                    this._onBeforeRenderObservable = new BABYLON.Observable();
                }
                return this._onBeforeRenderObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
            /**
            * An event triggered after rendering the mesh
            */
            get: function () {
                if (!this._onAfterRenderObservable) {
                    this._onAfterRenderObservable = new BABYLON.Observable();
                }
                return this._onAfterRenderObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
            /**
            * An event triggered before drawing the mesh
            */
            get: function () {
                if (!this._onBeforeDrawObservable) {
                    this._onBeforeDrawObservable = new BABYLON.Observable();
                }
                return this._onBeforeDrawObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
            /**
             * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
             */
            set: function (callback) {
                if (this._onBeforeDrawObserver) {
                    this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
                }
                this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "morphTargetManager", {
            /**
             * Gets or sets the morph target manager
             * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
             */
            get: function () {
                return this._morphTargetManager;
            },
            set: function (value) {
                if (this._morphTargetManager === value) {
                    return;
                }
                this._morphTargetManager = value;
                this._syncGeometryWithMorphTargetManager();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "source", {
            /**
             * Gets the source mesh (the one used to clone this one from)
             */
            get: function () {
                return this._source;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Mesh.prototype, "isUnIndexed", {
            /**
             * Gets or sets a boolean indicating that this mesh does not use index buffer
             */
            get: function () {
                return this._unIndexed;
            },
            set: function (value) {
                if (this._unIndexed !== value) {
                    this._unIndexed = value;
                    this._markSubMeshesAsAttributesDirty();
                }
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * Gets the class name
         * @returns the string "Mesh".
         */
        Mesh.prototype.getClassName = function () {
            return "Mesh";
        };
        /**
         * Returns a description of this mesh
         * @param fullDetails define if full details about this mesh must be used
         * @returns a descriptive string representing this mesh
         */
        Mesh.prototype.toString = function (fullDetails) {
            var ret = _super.prototype.toString.call(this, fullDetails);
            ret += ", n vertices: " + this.getTotalVertices();
            ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
            if (this.animations) {
                for (var i = 0; i < this.animations.length; i++) {
                    ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
                }
            }
            if (fullDetails) {
                if (this._geometry) {
                    var ib = this.getIndices();
                    var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                    if (vb && ib) {
                        ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
                    }
                }
                else {
                    ret += ", flat shading: UNKNOWN";
                }
            }
            return ret;
        };
        /** @hidden */
        Mesh.prototype._unBindEffect = function () {
            _super.prototype._unBindEffect.call(this);
            for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
                var instance = _a[_i];
                instance._unBindEffect();
            }
        };
        Object.defineProperty(Mesh.prototype, "hasLODLevels", {
            /**
             * Gets a boolean indicating if this mesh has LOD
             */
            get: function () {
                return this._LODLevels.length > 0;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the list of MeshLODLevel associated with the current mesh
         * @returns an array of MeshLODLevel
         */
        Mesh.prototype.getLODLevels = function () {
            return this._LODLevels;
        };
        Mesh.prototype._sortLODLevels = function () {
            this._LODLevels.sort(function (a, b) {
                if (a.distance < b.distance) {
                    return 1;
                }
                if (a.distance > b.distance) {
                    return -1;
                }
                return 0;
            });
        };
        /**
         * Add a mesh as LOD level triggered at the given distance.
         * @see https://doc.babylonjs.com/how_to/how_to_use_lod
         * @param distance The distance from the center of the object to show this level
         * @param mesh The mesh to be added as LOD level (can be null)
         * @return This mesh (for chaining)
         */
        Mesh.prototype.addLODLevel = function (distance, mesh) {
            if (mesh && mesh._masterMesh) {
                BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
                return this;
            }
            var level = new BABYLON.MeshLODLevel(distance, mesh);
            this._LODLevels.push(level);
            if (mesh) {
                mesh._masterMesh = this;
            }
            this._sortLODLevels();
            return this;
        };
        /**
         * Returns the LOD level mesh at the passed distance or null if not found.
         * @see https://doc.babylonjs.com/how_to/how_to_use_lod
         * @param distance The distance from the center of the object to show this level
         * @returns a Mesh or `null`
         */
        Mesh.prototype.getLODLevelAtDistance = function (distance) {
            for (var index = 0; index < this._LODLevels.length; index++) {
                var level = this._LODLevels[index];
                if (level.distance === distance) {
                    return level.mesh;
                }
            }
            return null;
        };
        /**
         * Remove a mesh from the LOD array
         * @see https://doc.babylonjs.com/how_to/how_to_use_lod
         * @param mesh defines the mesh to be removed
         * @return This mesh (for chaining)
         */
        Mesh.prototype.removeLODLevel = function (mesh) {
            for (var index = 0; index < this._LODLevels.length; index++) {
                if (this._LODLevels[index].mesh === mesh) {
                    this._LODLevels.splice(index, 1);
                    if (mesh) {
                        mesh._masterMesh = null;
                    }
                }
            }
            this._sortLODLevels();
            return this;
        };
        /**
         * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
         * @see https://doc.babylonjs.com/how_to/how_to_use_lod
         * @param camera defines the camera to use to compute distance
         * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
         * @return This mesh (for chaining)
         */
        Mesh.prototype.getLOD = function (camera, boundingSphere) {
            if (!this._LODLevels || this._LODLevels.length === 0) {
                return this;
            }
            var bSphere;
            if (boundingSphere) {
                bSphere = boundingSphere;
            }
            else {
                var boundingInfo = this.getBoundingInfo();
                bSphere = boundingInfo.boundingSphere;
            }
            var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
            if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
                if (this.onLODLevelSelection) {
                    this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
                }
                return this;
            }
            for (var index = 0; index < this._LODLevels.length; index++) {
                var level = this._LODLevels[index];
                if (level.distance < distanceToCamera) {
                    if (level.mesh) {
                        level.mesh._preActivate();
                        level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
                    }
                    if (this.onLODLevelSelection) {
                        this.onLODLevelSelection(distanceToCamera, this, level.mesh);
                    }
                    return level.mesh;
                }
            }
            if (this.onLODLevelSelection) {
                this.onLODLevelSelection(distanceToCamera, this, this);
            }
            return this;
        };
        Object.defineProperty(Mesh.prototype, "geometry", {
            /**
             * Gets the mesh internal Geometry object
             */
            get: function () {
                return this._geometry;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
         * @returns the total number of vertices
         */
        Mesh.prototype.getTotalVertices = function () {
            if (this._geometry === null || this._geometry === undefined) {
                return 0;
            }
            return this._geometry.getTotalVertices();
        };
        /**
         * Returns the content of an associated vertex buffer
         * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
         * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
         * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
         */
        Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
            if (!this._geometry) {
                return null;
            }
            return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
        };
        /**
         * Returns the mesh VertexBuffer object from the requested `kind`
         * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
         */
        Mesh.prototype.getVertexBuffer = function (kind) {
            if (!this._geometry) {
                return null;
            }
            return this._geometry.getVertexBuffer(kind);
        };
        /**
         * Tests if a specific vertex buffer is associated with this mesh
         * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @returns a boolean
         */
        Mesh.prototype.isVerticesDataPresent = function (kind) {
            if (!this._geometry) {
                if (this._delayInfo) {
                    return this._delayInfo.indexOf(kind) !== -1;
                }
                return false;
            }
            return this._geometry.isVerticesDataPresent(kind);
        };
        /**
         * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
         * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @returns a boolean
         */
        Mesh.prototype.isVertexBufferUpdatable = function (kind) {
            if (!this._geometry) {
                if (this._delayInfo) {
                    return this._delayInfo.indexOf(kind) !== -1;
                }
                return false;
            }
            return this._geometry.isVertexBufferUpdatable(kind);
        };
        /**
         * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
         * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @returns an array of strings
         */
        Mesh.prototype.getVerticesDataKinds = function () {
            if (!this._geometry) {
                var result = new Array();
                if (this._delayInfo) {
                    this._delayInfo.forEach(function (kind, index, array) {
                        result.push(kind);
                    });
                }
                return result;
            }
            return this._geometry.getVerticesDataKinds();
        };
        /**
         * Returns a positive integer : the total number of indices in this mesh geometry.
         * @returns the numner of indices or zero if the mesh has no geometry.
         */
        Mesh.prototype.getTotalIndices = function () {
            if (!this._geometry) {
                return 0;
            }
            return this._geometry.getTotalIndices();
        };
        /**
         * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
         * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
         * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
         * @returns the indices array or an empty array if the mesh has no geometry
         */
        Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
            if (!this._geometry) {
                return [];
            }
            return this._geometry.getIndices(copyWhenShared, forceCopy);
        };
        Object.defineProperty(Mesh.prototype, "isBlocked", {
            get: function () {
                return this._masterMesh !== null && this._masterMesh !== undefined;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Determine if the current mesh is ready to be rendered
         * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
         * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
         * @returns true if all associated assets are ready (material, textures, shaders)
         */
        Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
            if (completeCheck === void 0) { completeCheck = false; }
            if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                return false;
            }
            if (!_super.prototype.isReady.call(this, completeCheck)) {
                return false;
            }
            if (!this.subMeshes || this.subMeshes.length === 0) {
                return true;
            }
            if (!completeCheck) {
                return true;
            }
            var engine = this.getEngine();
            var scene = this.getScene();
            var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
            this.computeWorldMatrix();
            var mat = this.material || scene.defaultMaterial;
            if (mat) {
                if (mat.storeEffectOnSubMeshes) {
                    for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
                        var subMesh = _a[_i];
                        var effectiveMaterial = subMesh.getMaterial();
                        if (effectiveMaterial) {
                            if (effectiveMaterial.storeEffectOnSubMeshes) {
                                if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
                                    return false;
                                }
                            }
                            else {
                                if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
                                    return false;
                                }
                            }
                        }
                    }
                }
                else {
                    if (!mat.isReady(this, hardwareInstancedRendering)) {
                        return false;
                    }
                }
            }
            // Shadows
            for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
                var light = _c[_b];
                var generator = light.getShadowGenerator();
                if (generator) {
                    for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
                        var subMesh = _e[_d];
                        if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
                            return false;
                        }
                    }
                }
            }
            // LOD
            for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
                var lod = _g[_f];
                if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
                    return false;
                }
            }
            return true;
        };
        Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
            /**
             * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
             */
            get: function () {
                return this._areNormalsFrozen;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
         * @returns the current mesh
         */
        Mesh.prototype.freezeNormals = function () {
            this._areNormalsFrozen = true;
            return this;
        };
        /**
         * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
         * @returns the current mesh
         */
        Mesh.prototype.unfreezeNormals = function () {
            this._areNormalsFrozen = false;
            return this;
        };
        Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
            /**
             * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
             */
            set: function (count) {
                this._instanceDataStorage.overridenInstanceCount = count;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /** @hidden */
        Mesh.prototype._preActivate = function () {
            var sceneRenderId = this.getScene().getRenderId();
            if (this._preActivateId === sceneRenderId) {
                return this;
            }
            this._preActivateId = sceneRenderId;
            this._instanceDataStorage.visibleInstances = null;
            return this;
        };
        /** @hidden */
        Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
            if (this._instanceDataStorage.visibleInstances) {
                this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
            }
            return this;
        };
        /** @hidden */
        Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
            if (!this._instanceDataStorage.visibleInstances) {
                this._instanceDataStorage.visibleInstances = {};
                this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
                this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
            }
            if (!this._instanceDataStorage.visibleInstances[renderId]) {
                this._instanceDataStorage.visibleInstances[renderId] = new Array();
            }
            this._instanceDataStorage.visibleInstances[renderId].push(instance);
            return this;
        };
        /**
         * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
         * This means the mesh underlying bounding box and sphere are recomputed.
         * @returns the current mesh
         */
        Mesh.prototype.refreshBoundingInfo = function () {
            return this._refreshBoundingInfo(false);
        };
        /** @hidden */
        Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
            if (this._boundingInfo && this._boundingInfo.isLocked) {
                return this;
            }
            var data = this._getPositionData(applySkeleton);
            if (data) {
                var bias = this.geometry ? this.geometry.boundingBias : null;
                var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
                this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
            }
            if (this.subMeshes) {
                for (var index = 0; index < this.subMeshes.length; index++) {
                    this.subMeshes[index].refreshBoundingInfo();
                }
            }
            this._updateBoundingInfo();
            return this;
        };
        Mesh.prototype._getPositionData = function (applySkeleton) {
            var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (data && applySkeleton && this.skeleton) {
                data = BABYLON.Tools.Slice(data);
                var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
                var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (matricesWeightsData && matricesIndicesData) {
                    var needExtras = this.numBoneInfluencers > 4;
                    var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
                    var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
                    var skeletonMatrices = this.skeleton.getTransformMatrices(this);
                    var tempVector = BABYLON.Tmp.Vector3[0];
                    var finalMatrix = BABYLON.Tmp.Matrix[0];
                    var tempMatrix = BABYLON.Tmp.Matrix[1];
                    var matWeightIdx = 0;
                    for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
                        finalMatrix.reset();
                        var inf;
                        var weight;
                        for (inf = 0; inf < 4; inf++) {
                            weight = matricesWeightsData[matWeightIdx + inf];
                            if (weight > 0) {
                                BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
                                finalMatrix.addToSelf(tempMatrix);
                            }
                        }
                        if (needExtras) {
                            for (inf = 0; inf < 4; inf++) {
                                weight = matricesWeightsExtraData[matWeightIdx + inf];
                                if (weight > 0) {
                                    BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
                                    finalMatrix.addToSelf(tempMatrix);
                                }
                            }
                        }
                        BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
                        tempVector.toArray(data, index);
                    }
                }
            }
            return data;
        };
        /** @hidden */
        Mesh.prototype._createGlobalSubMesh = function (force) {
            var totalVertices = this.getTotalVertices();
            if (!totalVertices || !this.getIndices()) {
                return null;
            }
            // Check if we need to recreate the submeshes
            if (this.subMeshes && this.subMeshes.length > 0) {
                var ib = this.getIndices();
                if (!ib) {
                    return null;
                }
                var totalIndices = ib.length;
                var needToRecreate = false;
                if (force) {
                    needToRecreate = true;
                }
                else {
                    for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
                        var submesh = _a[_i];
                        if (submesh.indexStart + submesh.indexCount >= totalIndices) {
                            needToRecreate = true;
                            break;
                        }
                        if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
                            needToRecreate = true;
                            break;
                        }
                    }
                }
                if (!needToRecreate) {
                    return this.subMeshes[0];
                }
            }
            this.releaseSubMeshes();
            return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
        };
        /**
         * This function will subdivide the mesh into multiple submeshes
         * @param count defines the expected number of submeshes
         */
        Mesh.prototype.subdivide = function (count) {
            if (count < 1) {
                return;
            }
            var totalIndices = this.getTotalIndices();
            var subdivisionSize = (totalIndices / count) | 0;
            var offset = 0;
            // Ensure that subdivisionSize is a multiple of 3
            while (subdivisionSize % 3 !== 0) {
                subdivisionSize++;
            }
            this.releaseSubMeshes();
            for (var index = 0; index < count; index++) {
                if (offset >= totalIndices) {
                    break;
                }
                BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
                offset += subdivisionSize;
            }
            this.synchronizeInstances();
        };
        /**
         * Copy a FloatArray into a specific associated vertex buffer
         * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @param data defines the data source
         * @param updatable defines if the updated vertex buffer must be flagged as updatable
         * @param stride defines the data stride size (can be null)
         * @returns the current mesh
         */
        Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
            if (updatable === void 0) { updatable = false; }
            if (!this._geometry) {
                var vertexData = new BABYLON.VertexData();
                vertexData.set(data, kind);
                var scene = this.getScene();
                new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
            }
            else {
                this._geometry.setVerticesData(kind, data, updatable, stride);
            }
            return this;
        };
        /**
         * Flags an associated vertex buffer as updatable
         * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @param updatable defines if the updated vertex buffer must be flagged as updatable
         */
        Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
            if (updatable === void 0) { updatable = true; }
            var vb = this.getVertexBuffer(kind);
            if (!vb || vb.isUpdatable() === updatable) {
                return;
            }
            this.setVerticesData(kind, this.getVerticesData(kind), updatable);
        };
        /**
         * Sets the mesh global Vertex Buffer
         * @param buffer defines the buffer to use
         * @returns the current mesh
         */
        Mesh.prototype.setVerticesBuffer = function (buffer) {
            if (!this._geometry) {
                this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
            }
            this._geometry.setVerticesBuffer(buffer);
            return this;
        };
        /**
         * Update a specific associated vertex buffer
         * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         * @param data defines the data source
         * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
         * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
         * @returns the current mesh
         */
        Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
            if (!this._geometry) {
                return this;
            }
            if (!makeItUnique) {
                this._geometry.updateVerticesData(kind, data, updateExtends);
            }
            else {
                this.makeGeometryUnique();
                this.updateVerticesData(kind, data, updateExtends, false);
            }
            return this;
        };
        /**
         * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
         * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
         * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
         * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
         * @returns the current mesh
         */
        Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
            if (computeNormals === void 0) { computeNormals = true; }
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!positions) {
                return this;
            }
            positionFunction(positions);
            this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
            if (computeNormals) {
                var indices = this.getIndices();
                var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                if (!normals) {
                    return this;
                }
                BABYLON.VertexData.ComputeNormals(positions, indices, normals);
                this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
            }
            return this;
        };
        /**
         * Creates a un-shared specific occurence of the geometry for the mesh.
         * @returns the current mesh
         */
        Mesh.prototype.makeGeometryUnique = function () {
            if (!this._geometry) {
                return this;
            }
            var oldGeometry = this._geometry;
            var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
            oldGeometry.releaseForMesh(this, true);
            geometry.applyToMesh(this);
            return this;
        };
        /**
         * Set the index buffer of this mesh
         * @param indices defines the source data
         * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
         * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
         * @returns the current mesh
         */
        Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
            if (totalVertices === void 0) { totalVertices = null; }
            if (updatable === void 0) { updatable = false; }
            if (!this._geometry) {
                var vertexData = new BABYLON.VertexData();
                vertexData.indices = indices;
                var scene = this.getScene();
                new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
            }
            else {
                this._geometry.setIndices(indices, totalVertices, updatable);
            }
            return this;
        };
        /**
         * Update the current index buffer
         * @param indices defines the source data
         * @param offset defines the offset in the index buffer where to store the new data (can be null)
         * @returns the current mesh
         */
        Mesh.prototype.updateIndices = function (indices, offset) {
            if (!this._geometry) {
                return this;
            }
            this._geometry.updateIndices(indices, offset);
            return this;
        };
        /**
         * Invert the geometry to move from a right handed system to a left handed one.
         * @returns the current mesh
         */
        Mesh.prototype.toLeftHanded = function () {
            if (!this._geometry) {
                return this;
            }
            this._geometry.toLeftHanded();
            return this;
        };
        /** @hidden */
        Mesh.prototype._bind = function (subMesh, effect, fillMode) {
            if (!this._geometry) {
                return this;
            }
            var engine = this.getScene().getEngine();
            // Wireframe
            var indexToBind;
            if (this._unIndexed) {
                indexToBind = null;
            }
            else {
                switch (fillMode) {
                    case BABYLON.Material.PointFillMode:
                        indexToBind = null;
                        break;
                    case BABYLON.Material.WireFrameFillMode:
                        indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
                        break;
                    default:
                    case BABYLON.Material.TriangleFillMode:
                        indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
                        break;
                }
            }
            // VBOs
            this._geometry._bind(effect, indexToBind);
            return this;
        };
        /** @hidden */
        Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
            if (alternate === void 0) { alternate = false; }
            if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
                return this;
            }
            if (this._onBeforeDrawObservable) {
                this._onBeforeDrawObservable.notifyObservers(this);
            }
            var scene = this.getScene();
            var engine = scene.getEngine();
            if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
                // or triangles as points
                engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
            }
            else if (fillMode == BABYLON.Material.WireFrameFillMode) {
                // Triangles as wireframe
                engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
            }
            else {
                engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
            }
            if (scene._isAlternateRenderingEnabled && !alternate) {
                var effect = subMesh.effect || this._effectiveMaterial.getEffect();
                if (!effect || !scene.activeCamera) {
                    return this;
                }
                scene._switchToAlternateCameraConfiguration(true);
                this._effectiveMaterial.bindView(effect);
                this._effectiveMaterial.bindViewProjection(effect);
                engine.setViewport(scene.activeCamera._alternateCamera.viewport);
                this._draw(subMesh, fillMode, instancesCount, true);
                engine.setViewport(scene.activeCamera.viewport);
                scene._switchToAlternateCameraConfiguration(false);
                this._effectiveMaterial.bindView(effect);
                this._effectiveMaterial.bindViewProjection(effect);
            }
            return this;
        };
        /**
         * Registers for this mesh a javascript function called just before the rendering process
         * @param func defines the function to call before rendering this mesh
         * @returns the current mesh
         */
        Mesh.prototype.registerBeforeRender = function (func) {
            this.onBeforeRenderObservable.add(func);
            return this;
        };
        /**
         * Disposes a previously registered javascript function called before the rendering
         * @param func defines the function to remove
         * @returns the current mesh
         */
        Mesh.prototype.unregisterBeforeRender = function (func) {
            this.onBeforeRenderObservable.removeCallback(func);
            return this;
        };
        /**
         * Registers for this mesh a javascript function called just after the rendering is complete
         * @param func defines the function to call after rendering this mesh
         * @returns the current mesh
         */
        Mesh.prototype.registerAfterRender = function (func) {
            this.onAfterRenderObservable.add(func);
            return this;
        };
        /**
         * Disposes a previously registered javascript function called after the rendering.
         * @param func defines the function to remove
         * @returns the current mesh
         */
        Mesh.prototype.unregisterAfterRender = function (func) {
            this.onAfterRenderObservable.removeCallback(func);
            return this;
        };
        /** @hidden */
        Mesh.prototype._getInstancesRenderList = function (subMeshId) {
            var scene = this.getScene();
            var batchCache = this._instanceDataStorage.batchCache;
            batchCache.mustReturn = false;
            batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
            batchCache.visibleInstances[subMeshId] = null;
            if (this._instanceDataStorage.visibleInstances) {
                var visibleInstances = this._instanceDataStorage.visibleInstances;
                var currentRenderId = scene.getRenderId();
                var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
                batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
                var selfRenderId = this._renderId;
                if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
                    batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
                    currentRenderId = Math.max(defaultRenderId, currentRenderId);
                    selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
                }
                var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
                if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
                    if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
                        batchCache.mustReturn = true;
                        return batchCache;
                    }
                    if (currentRenderId !== selfRenderId) {
                        batchCache.renderSelf[subMeshId] = false;
                    }
                }
                this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
            }
            return batchCache;
        };
        /** @hidden */
        Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
            var visibleInstances = batch.visibleInstances[subMesh._id];
            if (!visibleInstances) {
                return this;
            }
            var matricesCount = visibleInstances.length + 1;
            var bufferSize = matricesCount * 16 * 4;
            var instanceStorage = this._instanceDataStorage;
            var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
            var instancesBuffer = instanceStorage.instancesBuffer;
            while (instanceStorage.instancesBufferSize < bufferSize) {
                instanceStorage.instancesBufferSize *= 2;
            }
            if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
                instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
            }
            var offset = 0;
            var instancesCount = 0;
            var world = this.getWorldMatrix();
            if (batch.renderSelf[subMesh._id]) {
                world.copyToArray(instanceStorage.instancesData, offset);
                offset += 16;
                instancesCount++;
            }
            if (visibleInstances) {
                for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
                    var instance = visibleInstances[instanceIndex];
                    instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
                    offset += 16;
                    instancesCount++;
                }
            }
            if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
                if (instancesBuffer) {
                    instancesBuffer.dispose();
                }
                instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
                instanceStorage.instancesBuffer = instancesBuffer;
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
                this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
            }
            else {
                instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
            }
            this._bind(subMesh, effect, fillMode);
            this._draw(subMesh, fillMode, instancesCount);
            engine.unbindInstanceAttributes();
            return this;
        };
        /** @hidden */
        Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
            var scene = this.getScene();
            var engine = scene.getEngine();
            if (hardwareInstancedRendering) {
                this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
            }
            else {
                if (batch.renderSelf[subMesh._id]) {
                    // Draw
                    if (onBeforeDraw) {
                        onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
                    }
                    this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
                }
                var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
                if (visibleInstancesForSubMesh) {
                    for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
                        var instance = visibleInstancesForSubMesh[instanceIndex];
                        // World
                        var world = instance.getWorldMatrix();
                        if (onBeforeDraw) {
                            onBeforeDraw(true, world, effectiveMaterial);
                        }
                        // Draw
                        this._draw(subMesh, fillMode);
                    }
                }
            }
            return this;
        };
        /**
         * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
         * @param subMesh defines the subMesh to render
         * @param enableAlphaMode defines if alpha mode can be changed
         * @returns the current mesh
         */
        Mesh.prototype.render = function (subMesh, enableAlphaMode) {
            if (this._checkOcclusionQuery()) {
                return this;
            }
            var scene = this.getScene();
            // Managing instances
            var batch = this._getInstancesRenderList(subMesh._id);
            if (batch.mustReturn) {
                return this;
            }
            // Checking geometry state
            if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
                return this;
            }
            if (this._onBeforeRenderObservable) {
                this._onBeforeRenderObservable.notifyObservers(this);
            }
            var engine = scene.getEngine();
            var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
            // Material
            var material = subMesh.getMaterial();
            if (!material) {
                return this;
            }
            this._effectiveMaterial = material;
            if (this._effectiveMaterial.storeEffectOnSubMeshes) {
                if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
                    return this;
                }
            }
            else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
                return this;
            }
            // Alpha mode
            if (enableAlphaMode) {
                engine.setAlphaMode(this._effectiveMaterial.alphaMode);
            }
            for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
                var step = _a[_i];
                step.action(this, subMesh, batch);
            }
            var effect;
            if (this._effectiveMaterial.storeEffectOnSubMeshes) {
                effect = subMesh.effect;
            }
            else {
                effect = this._effectiveMaterial.getEffect();
            }
            if (!effect) {
                return this;
            }
            var sideOrientation = this.overrideMaterialSideOrientation;
            if (sideOrientation == null) {
                sideOrientation = this._effectiveMaterial.sideOrientation;
                if (this._getWorldMatrixDeterminant() < 0) {
                    sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
                }
            }
            var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
            if (this._effectiveMaterial.forceDepthWrite) {
                engine.setDepthWrite(true);
            }
            // Bind
            var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
            if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
                this._bind(subMesh, effect, fillMode);
            }
            var world = this.getWorldMatrix();
            if (this._effectiveMaterial.storeEffectOnSubMeshes) {
                this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
            }
            else {
                this._effectiveMaterial.bind(world, this);
            }
            if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
                engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
                this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
                engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
            }
            // Draw
            this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
            // Unbind
            this._effectiveMaterial.unbind();
            for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
                var step = _c[_b];
                step.action(this, subMesh, batch);
            }
            if (this._onAfterRenderObservable) {
                this._onAfterRenderObservable.notifyObservers(this);
            }
            return this;
        };
        Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
            if (isInstance && effectiveMaterial) {
                effectiveMaterial.bindOnlyWorldMatrix(world);
            }
        };
        /**
         *   Renormalize the mesh and patch it up if there are no weights
         *   Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
         *   However in the case of zero weights then we set just a single influence to 1.
         *   We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
         */
        Mesh.prototype.cleanMatrixWeights = function () {
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
                    this.normalizeSkinWeightsAndExtra();
                }
                else {
                    this.normalizeSkinFourWeights();
                }
            }
        };
        // faster 4 weight version.
        Mesh.prototype.normalizeSkinFourWeights = function () {
            var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
            var numWeights = matricesWeights.length;
            for (var a = 0; a < numWeights; a += 4) {
                // accumulate weights
                var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
                // check for invalid weight and just set it to 1.
                if (t === 0) {
                    matricesWeights[a] = 1;
                }
                else {
                    // renormalize so everything adds to 1 use reciprical
                    var recip = 1 / t;
                    matricesWeights[a] *= recip;
                    matricesWeights[a + 1] *= recip;
                    matricesWeights[a + 2] *= recip;
                    matricesWeights[a + 3] *= recip;
                }
            }
            this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
        };
        // handle special case of extra verts.  (in theory gltf can handle 12 influences)
        Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
            var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
            var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
            var numWeights = matricesWeights.length;
            for (var a = 0; a < numWeights; a += 4) {
                // accumulate weights
                var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
                t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
                // check for invalid weight and just set it to 1.
                if (t === 0) {
                    matricesWeights[a] = 1;
                }
                else {
                    // renormalize so everything adds to 1 use reciprical
                    var recip = 1 / t;
                    matricesWeights[a] *= recip;
                    matricesWeights[a + 1] *= recip;
                    matricesWeights[a + 2] *= recip;
                    matricesWeights[a + 3] *= recip;
                    // same goes for extras
                    matricesWeightsExtra[a] *= recip;
                    matricesWeightsExtra[a + 1] *= recip;
                    matricesWeightsExtra[a + 2] *= recip;
                    matricesWeightsExtra[a + 3] *= recip;
                }
            }
            this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
            this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
        };
        /**
         * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
         * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
         * the user know there was an issue with importing the mesh
         * @returns a validation object with skinned, valid and report string
         */
        Mesh.prototype.validateSkinning = function () {
            var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
            var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
            if (matricesWeights === null || this.skeleton == null) {
                return { skinned: false, valid: true, report: "not skinned" };
            }
            var numWeights = matricesWeights.length;
            var numberNotSorted = 0;
            var missingWeights = 0;
            var maxUsedWeights = 0;
            var numberNotNormalized = 0;
            var numInfluences = matricesWeightsExtra === null ? 4 : 8;
            var usedWeightCounts = new Array();
            for (var a = 0; a <= numInfluences; a++) {
                usedWeightCounts[a] = 0;
            }
            var toleranceEpsilon = 0.001;
            for (var a = 0; a < numWeights; a += 4) {
                var lastWeight = matricesWeights[a];
                var t = lastWeight;
                var usedWeights = t === 0 ? 0 : 1;
                for (var b = 1; b < numInfluences; b++) {
                    var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
                    if (d > lastWeight) {
                        numberNotSorted++;
                    }
                    if (d !== 0) {
                        usedWeights++;
                    }
                    t += d;
                    lastWeight = d;
                }
                // count the buffer weights usage
                usedWeightCounts[usedWeights]++;
                // max influences
                if (usedWeights > maxUsedWeights) {
                    maxUsedWeights = usedWeights;
                }
                // check for invalid weight and just set it to 1.
                if (t === 0) {
                    missingWeights++;
                }
                else {
                    // renormalize so everything adds to 1 use reciprical
                    var recip = 1 / t;
                    var tolerance = 0;
                    for (b = 0; b < numInfluences; b++) {
                        if (b < 4) {
                            tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
                        }
                        else {
                            tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
                        }
                    }
                    // arbitary epsilon value for dicdating not normalized
                    if (tolerance > toleranceEpsilon) {
                        numberNotNormalized++;
                    }
                }
            }
            // validate bone indices are in range of the skeleton
            var numBones = this.skeleton.bones.length;
            var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
            var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
            var numBadBoneIndices = 0;
            for (var a = 0; a < numWeights; a++) {
                for (var b = 0; b < numInfluences; b++) {
                    var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
                    if (index >= numBones || index < 0) {
                        numBadBoneIndices++;
                    }
                }
            }
            // log mesh stats
            var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
                "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
                "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
                "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
            return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
        };
        /** @hidden */
        Mesh.prototype._checkDelayState = function () {
            var scene = this.getScene();
            if (this._geometry) {
                this._geometry.load(scene);
            }
            else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
                this._queueLoad(scene);
            }
            return this;
        };
        Mesh.prototype._queueLoad = function (scene) {
            var _this = this;
            scene._addPendingData(this);
            var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
            BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
                if (data instanceof ArrayBuffer) {
                    _this._delayLoadingFunction(data, _this);
                }
                else {
                    _this._delayLoadingFunction(JSON.parse(data), _this);
                }
                _this.instances.forEach(function (instance) {
                    instance._syncSubMeshes();
                });
                _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
                scene._removePendingData(_this);
            }, function () { }, scene.database, getBinaryData);
            return this;
        };
        /**
         * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
         * A mesh is in the frustum if its bounding box intersects the frustum
         * @param frustumPlanes defines the frustum to test
         * @returns true if the mesh is in the frustum planes
         */
        Mesh.prototype.isInFrustum = function (frustumPlanes) {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                return false;
            }
            if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
                return false;
            }
            this._checkDelayState();
            return true;
        };
        /**
         * Sets the mesh material by the material or multiMaterial `id` property
         * @param id is a string identifying the material or the multiMaterial
         * @returns the current mesh
         */
        Mesh.prototype.setMaterialByID = function (id) {
            var materials = this.getScene().materials;
            var index;
            for (index = materials.length - 1; index > -1; index--) {
                if (materials[index].id === id) {
                    this.material = materials[index];
                    return this;
                }
            }
            // Multi
            var multiMaterials = this.getScene().multiMaterials;
            for (index = multiMaterials.length - 1; index > -1; index--) {
                if (multiMaterials[index].id === id) {
                    this.material = multiMaterials[index];
                    return this;
                }
            }
            return this;
        };
        /**
         * Returns as a new array populated with the mesh material and/or skeleton, if any.
         * @returns an array of IAnimatable
         */
        Mesh.prototype.getAnimatables = function () {
            var results = new Array();
            if (this.material) {
                results.push(this.material);
            }
            if (this.skeleton) {
                results.push(this.skeleton);
            }
            return results;
        };
        /**
         * Modifies the mesh geometry according to the passed transformation matrix.
         * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
         * The mesh normals are modified using the same transformation.
         * Note that, under the hood, this method sets a new VertexBuffer each call.
         * @param transform defines the transform matrix to use
         * @see http://doc.babylonjs.com/resources/baking_transformations
         * @returns the current mesh
         */
        Mesh.prototype.bakeTransformIntoVertices = function (transform) {
            // Position
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                return this;
            }
            var submeshes = this.subMeshes.splice(0);
            this._resetPointsArrayCache();
            var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var temp = new Array();
            var index;
            for (index = 0; index < data.length; index += 3) {
                BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
            }
            this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
            // Normals
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                temp = [];
                for (index = 0; index < data.length; index += 3) {
                    BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
                }
                this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
            }
            // flip faces?
            if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
                this.flipFaces();
            }
            // Restore submeshes
            this.releaseSubMeshes();
            this.subMeshes = submeshes;
            return this;
        };
        /**
         * Modifies the mesh geometry according to its own current World Matrix.
         * The mesh World Matrix is then reset.
         * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
         * Note that, under the hood, this method sets a new VertexBuffer each call.
         * @see http://doc.babylonjs.com/resources/baking_transformations
         * @returns the current mesh
         */
        Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
            this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
            this.scaling.copyFromFloats(1, 1, 1);
            this.position.copyFromFloats(0, 0, 0);
            this.rotation.copyFromFloats(0, 0, 0);
            //only if quaternion is already set
            if (this.rotationQuaternion) {
                this.rotationQuaternion = BABYLON.Quaternion.Identity();
            }
            this._worldMatrix = BABYLON.Matrix.Identity();
            return this;
        };
        Object.defineProperty(Mesh.prototype, "_positions", {
            // Cache
            /** @hidden */
            get: function () {
                if (this._geometry) {
                    return this._geometry._positions;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Mesh.prototype._resetPointsArrayCache = function () {
            if (this._geometry) {
                this._geometry._resetPointsArrayCache();
            }
            return this;
        };
        /** @hidden */
        Mesh.prototype._generatePointsArray = function () {
            if (this._geometry) {
                return this._geometry._generatePointsArray();
            }
            return false;
        };
        /**
         * Returns a new Mesh object generated from the current mesh properties.
         * This method must not get confused with createInstance()
         * @param name is a string, the name given to the new mesh
         * @param newParent can be any Node object (default `null`)
         * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
         * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
         * @returns a new mesh
         */
        Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
            if (name === void 0) { name = ""; }
            if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
            return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
        };
        /**
         * Releases resources associated with this mesh.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            var _this = this;
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            this.morphTargetManager = null;
            if (this._geometry) {
                this._geometry.releaseForMesh(this, true);
            }
            if (this._onBeforeDrawObservable) {
                this._onBeforeDrawObservable.clear();
            }
            if (this._onBeforeRenderObservable) {
                this._onBeforeRenderObservable.clear();
            }
            if (this._onAfterRenderObservable) {
                this._onAfterRenderObservable.clear();
            }
            // Sources
            var meshes = this.getScene().meshes;
            meshes.forEach(function (abstractMesh) {
                var mesh = abstractMesh;
                if (mesh._source && mesh._source === _this) {
                    mesh._source = null;
                }
            });
            this._source = null;
            // Instances
            if (this._instanceDataStorage.instancesBuffer) {
                this._instanceDataStorage.instancesBuffer.dispose();
                this._instanceDataStorage.instancesBuffer = null;
            }
            while (this.instances.length) {
                this.instances[0].dispose();
            }
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        /**
         * Modifies the mesh geometry according to a displacement map.
         * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
         * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
         * @param url is a string, the URL from the image file is to be downloaded.
         * @param minHeight is the lower limit of the displacement.
         * @param maxHeight is the upper limit of the displacement.
         * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
         * @param uvOffset is an optional vector2 used to offset UV.
         * @param uvScale is an optional vector2 used to scale UV.
         * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
         * @returns the Mesh.
         */
        Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
            var _this = this;
            if (forceUpdate === void 0) { forceUpdate = false; }
            var scene = this.getScene();
            var onload = function (img) {
                // Getting height map data
                var canvas = document.createElement("canvas");
                var context = canvas.getContext("2d");
                var heightMapWidth = img.width;
                var heightMapHeight = img.height;
                canvas.width = heightMapWidth;
                canvas.height = heightMapHeight;
                context.drawImage(img, 0, 0);
                // Create VertexData from map data
                //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
                var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
                _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
                //execute success callback, if set
                if (onSuccess) {
                    onSuccess(_this);
                }
            };
            BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
            return this;
        };
        /**
         * Modifies the mesh geometry according to a displacementMap buffer.
         * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
         * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
         * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
         * @param heightMapWidth is the width of the buffer image.
         * @param heightMapHeight is the height of the buffer image.
         * @param minHeight is the lower limit of the displacement.
         * @param maxHeight is the upper limit of the displacement.
         * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
         * @param uvOffset is an optional vector2 used to offset UV.
         * @param uvScale is an optional vector2 used to scale UV.
         * @param forceUpdate defines whether or not to force an update of the generated buffers. This is usefull to apply on a deserialized model for instance.
         * @returns the Mesh.
         */
        Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
            if (forceUpdate === void 0) { forceUpdate = false; }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
                || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
                || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
                return this;
            }
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
            var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var position = BABYLON.Vector3.Zero();
            var normal = BABYLON.Vector3.Zero();
            var uv = BABYLON.Vector2.Zero();
            uvOffset = uvOffset || BABYLON.Vector2.Zero();
            uvScale = uvScale || new BABYLON.Vector2(1, 1);
            for (var index = 0; index < positions.length; index += 3) {
                BABYLON.Vector3.FromArrayToRef(positions, index, position);
                BABYLON.Vector3.FromArrayToRef(normals, index, normal);
                BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
                // Compute height
                var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
                var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
                var pos = (u + v * heightMapWidth) * 4;
                var r = buffer[pos] / 255.0;
                var g = buffer[pos + 1] / 255.0;
                var b = buffer[pos + 2] / 255.0;
                var gradient = r * 0.3 + g * 0.59 + b * 0.11;
                normal.normalize();
                normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
                position = position.add(normal);
                position.toArray(positions, index);
            }
            BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
            if (forceUpdate) {
                this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
                this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
            }
            else {
                this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
                this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
            }
            return this;
        };
        /**
         * Modify the mesh to get a flat shading rendering.
         * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
         * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
         * @returns current mesh
         */
        Mesh.prototype.convertToFlatShadedMesh = function () {
            var kinds = this.getVerticesDataKinds();
            var vbs = {};
            var data = {};
            var newdata = {};
            var updatableNormals = false;
            var kindIndex;
            var kind;
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                var vertexBuffer = this.getVertexBuffer(kind);
                if (kind === BABYLON.VertexBuffer.NormalKind) {
                    updatableNormals = vertexBuffer.isUpdatable();
                    kinds.splice(kindIndex, 1);
                    kindIndex--;
                    continue;
                }
                vbs[kind] = vertexBuffer;
                data[kind] = vbs[kind].getData();
                newdata[kind] = [];
            }
            // Save previous submeshes
            var previousSubmeshes = this.subMeshes.slice(0);
            var indices = this.getIndices();
            var totalIndices = this.getTotalIndices();
            // Generating unique vertices per face
            var index;
            for (index = 0; index < totalIndices; index++) {
                var vertexIndex = indices[index];
                for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                    kind = kinds[kindIndex];
                    var stride = vbs[kind].getStrideSize();
                    for (var offset = 0; offset < stride; offset++) {
                        newdata[kind].push(data[kind][vertexIndex * stride + offset]);
                    }
                }
            }
            // Updating faces & normal
            var normals = [];
            var positions = newdata[BABYLON.VertexBuffer.PositionKind];
            for (index = 0; index < totalIndices; index += 3) {
                indices[index] = index;
                indices[index + 1] = index + 1;
                indices[index + 2] = index + 2;
                var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
                var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
                var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
                var p1p2 = p1.subtract(p2);
                var p3p2 = p3.subtract(p2);
                var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
                // Store same normals for every vertex
                for (var localIndex = 0; localIndex < 3; localIndex++) {
                    normals.push(normal.x);
                    normals.push(normal.y);
                    normals.push(normal.z);
                }
            }
            this.setIndices(indices);
            this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
            // Updating vertex buffers
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
            }
            // Updating submeshes
            this.releaseSubMeshes();
            for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
                var previousOne = previousSubmeshes[submeshIndex];
                BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
            }
            this.synchronizeInstances();
            return this;
        };
        /**
         * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
         * In other words, more vertices, no more indices and a single bigger VBO.
         * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
         * @returns current mesh
         */
        Mesh.prototype.convertToUnIndexedMesh = function () {
            var kinds = this.getVerticesDataKinds();
            var vbs = {};
            var data = {};
            var newdata = {};
            var kindIndex;
            var kind;
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                var vertexBuffer = this.getVertexBuffer(kind);
                vbs[kind] = vertexBuffer;
                data[kind] = vbs[kind].getData();
                newdata[kind] = [];
            }
            // Save previous submeshes
            var previousSubmeshes = this.subMeshes.slice(0);
            var indices = this.getIndices();
            var totalIndices = this.getTotalIndices();
            // Generating unique vertices per face
            var index;
            for (index = 0; index < totalIndices; index++) {
                var vertexIndex = indices[index];
                for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                    kind = kinds[kindIndex];
                    var stride = vbs[kind].getStrideSize();
                    for (var offset = 0; offset < stride; offset++) {
                        newdata[kind].push(data[kind][vertexIndex * stride + offset]);
                    }
                }
            }
            // Updating indices
            for (index = 0; index < totalIndices; index += 3) {
                indices[index] = index;
                indices[index + 1] = index + 1;
                indices[index + 2] = index + 2;
            }
            this.setIndices(indices);
            // Updating vertex buffers
            for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
                kind = kinds[kindIndex];
                this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
            }
            // Updating submeshes
            this.releaseSubMeshes();
            for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
                var previousOne = previousSubmeshes[submeshIndex];
                BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
            }
            this._unIndexed = true;
            this.synchronizeInstances();
            return this;
        };
        /**
         * Inverses facet orientations.
         * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
         * @param flipNormals will also inverts the normals
         * @returns current mesh
         */
        Mesh.prototype.flipFaces = function (flipNormals) {
            if (flipNormals === void 0) { flipNormals = false; }
            var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
            var i;
            if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
                for (i = 0; i < vertex_data.normals.length; i++) {
                    vertex_data.normals[i] *= -1;
                }
            }
            if (vertex_data.indices) {
                var temp;
                for (i = 0; i < vertex_data.indices.length; i += 3) {
                    // reassign indices
                    temp = vertex_data.indices[i + 1];
                    vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
                    vertex_data.indices[i + 2] = temp;
                }
            }
            vertex_data.applyToMesh(this);
            return this;
        };
        // Instances
        /**
         * Creates a new InstancedMesh object from the mesh model.
         * Warning : this method is not supported for Line mesh and LineSystem
         * @see http://doc.babylonjs.com/how_to/how_to_use_instances
         * @param name defines the name of the new instance
         * @returns a new InstancedMesh
         */
        Mesh.prototype.createInstance = function (name) {
            return new BABYLON.InstancedMesh(name, this);
        };
        /**
         * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
         * After this call, all the mesh instances have the same submeshes than the current mesh.
         * @returns the current mesh
         */
        Mesh.prototype.synchronizeInstances = function () {
            for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
                var instance = this.instances[instanceIndex];
                instance._syncSubMeshes();
            }
            return this;
        };
        /**
         * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
         * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
         * This should be used together with the simplification to avoid disappearing triangles.
         * @param successCallback an optional success callback to be called after the optimization finished.
         * @returns the current mesh
         */
        Mesh.prototype.optimizeIndices = function (successCallback) {
            var _this = this;
            var indices = this.getIndices();
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!positions || !indices) {
                return this;
            }
            var vectorPositions = new Array();
            for (var pos = 0; pos < positions.length; pos = pos + 3) {
                vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
            }
            var dupes = new Array();
            BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
                var realPos = vectorPositions.length - 1 - iteration;
                var testedPosition = vectorPositions[realPos];
                for (var j = 0; j < realPos; ++j) {
                    var againstPosition = vectorPositions[j];
                    if (testedPosition.equals(againstPosition)) {
                        dupes[realPos] = j;
                        break;
                    }
                }
            }, function () {
                for (var i = 0; i < indices.length; ++i) {
                    indices[i] = dupes[indices[i]] || indices[i];
                }
                //indices are now reordered
                var originalSubMeshes = _this.subMeshes.slice(0);
                _this.setIndices(indices);
                _this.subMeshes = originalSubMeshes;
                if (successCallback) {
                    successCallback(_this);
                }
            });
            return this;
        };
        /**
         * Serialize current mesh
         * @param serializationObject defines the object which will receive the serialization data
         */
        Mesh.prototype.serialize = function (serializationObject) {
            serializationObject.name = this.name;
            serializationObject.id = this.id;
            serializationObject.type = this.getClassName();
            if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
                serializationObject.tags = BABYLON.Tags.GetTags(this);
            }
            serializationObject.position = this.position.asArray();
            if (this.rotationQuaternion) {
                serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
            }
            else if (this.rotation) {
                serializationObject.rotation = this.rotation.asArray();
            }
            serializationObject.scaling = this.scaling.asArray();
            serializationObject.localMatrix = this.getPivotMatrix().asArray();
            serializationObject.isEnabled = this.isEnabled(false);
            serializationObject.isVisible = this.isVisible;
            serializationObject.infiniteDistance = this.infiniteDistance;
            serializationObject.pickable = this.isPickable;
            serializationObject.receiveShadows = this.receiveShadows;
            serializationObject.billboardMode = this.billboardMode;
            serializationObject.visibility = this.visibility;
            serializationObject.checkCollisions = this.checkCollisions;
            serializationObject.isBlocker = this.isBlocker;
            // Parent
            if (this.parent) {
                serializationObject.parentId = this.parent.id;
            }
            // Geometry
            serializationObject.isUnIndexed = this.isUnIndexed;
            var geometry = this._geometry;
            if (geometry) {
                var geometryId = geometry.id;
                serializationObject.geometryId = geometryId;
                // SubMeshes
                serializationObject.subMeshes = [];
                for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
                    var subMesh = this.subMeshes[subIndex];
                    serializationObject.subMeshes.push({
                        materialIndex: subMesh.materialIndex,
                        verticesStart: subMesh.verticesStart,
                        verticesCount: subMesh.verticesCount,
                        indexStart: subMesh.indexStart,
                        indexCount: subMesh.indexCount
                    });
                }
            }
            // Material
            if (this.material) {
                serializationObject.materialId = this.material.id;
            }
            else {
                this.material = null;
            }
            // Morph targets
            if (this.morphTargetManager) {
                serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
            }
            // Skeleton
            if (this.skeleton) {
                serializationObject.skeletonId = this.skeleton.id;
            }
            // Physics
            //TODO implement correct serialization for physics impostors.
            var impostor = this.getPhysicsImpostor();
            if (impostor) {
                serializationObject.physicsMass = impostor.getParam("mass");
                serializationObject.physicsFriction = impostor.getParam("friction");
                serializationObject.physicsRestitution = impostor.getParam("mass");
                serializationObject.physicsImpostor = impostor.type;
            }
            // Metadata
            if (this.metadata) {
                serializationObject.metadata = this.metadata;
            }
            // Instances
            serializationObject.instances = [];
            for (var index = 0; index < this.instances.length; index++) {
                var instance = this.instances[index];
                if (instance.doNotSerialize) {
                    continue;
                }
                var serializationInstance = {
                    name: instance.name,
                    id: instance.id,
                    position: instance.position.asArray(),
                    scaling: instance.scaling.asArray()
                };
                if (instance.parent) {
                    serializationInstance.parentId = instance.parent.id;
                }
                if (instance.rotationQuaternion) {
                    serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
                }
                else if (instance.rotation) {
                    serializationInstance.rotation = instance.rotation.asArray();
                }
                serializationObject.instances.push(serializationInstance);
                // Animations
                BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
                serializationInstance.ranges = instance.serializeAnimationRanges();
            }
            //
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            serializationObject.ranges = this.serializeAnimationRanges();
            // Layer mask
            serializationObject.layerMask = this.layerMask;
            // Alpha
            serializationObject.alphaIndex = this.alphaIndex;
            serializationObject.hasVertexAlpha = this.hasVertexAlpha;
            // Overlay
            serializationObject.overlayAlpha = this.overlayAlpha;
            serializationObject.overlayColor = this.overlayColor.asArray();
            serializationObject.renderOverlay = this.renderOverlay;
            // Fog
            serializationObject.applyFog = this.applyFog;
            // Action Manager
            if (this.actionManager) {
                serializationObject.actions = this.actionManager.serialize(this.name);
            }
        };
        /** @hidden */
        Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
            if (!this.geometry) {
                return;
            }
            this._markSubMeshesAsAttributesDirty();
            var morphTargetManager = this._morphTargetManager;
            if (morphTargetManager && morphTargetManager.vertexCount) {
                if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
                    BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
                    this.morphTargetManager = null;
                    return;
                }
                for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
                    var morphTarget = morphTargetManager.getActiveTarget(index);
                    var positions = morphTarget.getPositions();
                    if (!positions) {
                        BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
                        return;
                    }
                    this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
                    var normals = morphTarget.getNormals();
                    if (normals) {
                        this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
                    }
                    var tangents = morphTarget.getTangents();
                    if (tangents) {
                        this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
                    }
                }
            }
            else {
                var index = 0;
                // Positions
                while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
                    this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
                    if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
                        this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
                    }
                    if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
                        this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
                    }
                    index++;
                }
            }
        };
        // Statics
        /**
         * Returns a new Mesh object parsed from the source provided.
         * @param parsedMesh is the source
         * @param scene defines the hosting scene
         * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
         * @returns a new Mesh
         */
        Mesh.Parse = function (parsedMesh, scene, rootUrl) {
            var mesh;
            if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
                mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
            }
            else {
                mesh = new Mesh(parsedMesh.name, scene);
            }
            mesh.id = parsedMesh.id;
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
            }
            mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
            if (parsedMesh.metadata !== undefined) {
                mesh.metadata = parsedMesh.metadata;
            }
            if (parsedMesh.rotationQuaternion) {
                mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
            }
            else if (parsedMesh.rotation) {
                mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
            }
            mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
            if (parsedMesh.localMatrix) {
                mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
            }
            else if (parsedMesh.pivotMatrix) {
                mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
            }
            mesh.setEnabled(parsedMesh.isEnabled);
            mesh.isVisible = parsedMesh.isVisible;
            mesh.infiniteDistance = parsedMesh.infiniteDistance;
            mesh.showBoundingBox = parsedMesh.showBoundingBox;
            mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
            if (parsedMesh.applyFog !== undefined) {
                mesh.applyFog = parsedMesh.applyFog;
            }
            if (parsedMesh.pickable !== undefined) {
                mesh.isPickable = parsedMesh.pickable;
            }
            if (parsedMesh.alphaIndex !== undefined) {
                mesh.alphaIndex = parsedMesh.alphaIndex;
            }
            mesh.receiveShadows = parsedMesh.receiveShadows;
            mesh.billboardMode = parsedMesh.billboardMode;
            if (parsedMesh.visibility !== undefined) {
                mesh.visibility = parsedMesh.visibility;
            }
            mesh.checkCollisions = parsedMesh.checkCollisions;
            if (parsedMesh.isBlocker !== undefined) {
                mesh.isBlocker = parsedMesh.isBlocker;
            }
            mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
            // freezeWorldMatrix
            if (parsedMesh.freezeWorldMatrix) {
                mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
            }
            // Parent
            if (parsedMesh.parentId) {
                mesh._waitingParentId = parsedMesh.parentId;
            }
            // Actions
            if (parsedMesh.actions !== undefined) {
                mesh._waitingActions = parsedMesh.actions;
            }
            // Overlay
            if (parsedMesh.overlayAlpha !== undefined) {
                mesh.overlayAlpha = parsedMesh.overlayAlpha;
            }
            if (parsedMesh.overlayColor !== undefined) {
                mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
            }
            if (parsedMesh.renderOverlay !== undefined) {
                mesh.renderOverlay = parsedMesh.renderOverlay;
            }
            // Geometry
            mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
            mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
            if (parsedMesh.delayLoadingFile) {
                mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
                mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
                if (parsedMesh._binaryInfo) {
                    mesh._binaryInfo = parsedMesh._binaryInfo;
                }
                mesh._delayInfo = [];
                if (parsedMesh.hasUVs) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
                }
                if (parsedMesh.hasUVs2) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (parsedMesh.hasUVs3) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
                }
                if (parsedMesh.hasUVs4) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
                }
                if (parsedMesh.hasUVs5) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
                }
                if (parsedMesh.hasUVs6) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
                }
                if (parsedMesh.hasColors) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
                }
                if (parsedMesh.hasMatricesIndices) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                }
                if (parsedMesh.hasMatricesWeights) {
                    mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                }
                mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
                if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
                    mesh._checkDelayState();
                }
            }
            else {
                BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
            }
            // Material
            if (parsedMesh.materialId) {
                mesh.setMaterialByID(parsedMesh.materialId);
            }
            else {
                mesh.material = null;
            }
            // Morph targets
            if (parsedMesh.morphTargetManagerId > -1) {
                mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
            }
            // Skeleton
            if (parsedMesh.skeletonId > -1) {
                mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
                if (parsedMesh.numBoneInfluencers) {
                    mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
                }
            }
            // Animations
            if (parsedMesh.animations) {
                for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
                    var parsedAnimation = parsedMesh.animations[animationIndex];
                    mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
            }
            if (parsedMesh.autoAnimate) {
                scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
            }
            // Layer Mask
            if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
                mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
            }
            else {
                mesh.layerMask = 0x0FFFFFFF;
            }
            // Physics
            if (parsedMesh.physicsImpostor) {
                mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
                    mass: parsedMesh.physicsMass,
                    friction: parsedMesh.physicsFriction,
                    restitution: parsedMesh.physicsRestitution
                }, scene);
            }
            // Instances
            if (parsedMesh.instances) {
                for (var index = 0; index < parsedMesh.instances.length; index++) {
                    var parsedInstance = parsedMesh.instances[index];
                    var instance = mesh.createInstance(parsedInstance.name);
                    if (parsedInstance.id) {
                        instance.id = parsedInstance.id;
                    }
                    if (BABYLON.Tags) {
                        if (parsedInstance.tags) {
                            BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
                        }
                        else {
                            BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
                        }
                    }
                    instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
                    if (parsedInstance.parentId) {
                        instance._waitingParentId = parsedInstance.parentId;
                    }
                    if (parsedInstance.rotationQuaternion) {
                        instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
                    }
                    else if (parsedInstance.rotation) {
                        instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
                    }
                    instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
                    if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
                        instance.checkCollisions = parsedInstance.checkCollisions;
                    }
                    if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
                        instance.isPickable = parsedInstance.pickable;
                    }
                    if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
                        instance.showBoundingBox = parsedInstance.showBoundingBox;
                    }
                    if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
                        instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
                    }
                    if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
                        instance.alphaIndex = parsedInstance.alphaIndex;
                    }
                    // Physics
                    if (parsedInstance.physicsImpostor) {
                        instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
                            mass: parsedInstance.physicsMass,
                            friction: parsedInstance.physicsFriction,
                            restitution: parsedInstance.physicsRestitution
                        }, scene);
                    }
                    // Animation
                    if (parsedInstance.animations) {
                        for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
                            parsedAnimation = parsedInstance.animations[animationIndex];
                            instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                        }
                        BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
                        if (parsedInstance.autoAnimate) {
                            scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
                        }
                    }
                }
            }
            return mesh;
        };
        /**
         * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
         * @see http://doc.babylonjs.com/how_to/parametric_shapes
         * @param name defines the name of the mesh to create
         * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
         * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
         * @param closePath creates a seam between the first and the last points of each path of the path array
         * @param offset is taken in account only if the `pathArray` is containing a single path
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
         * @returns a new Mesh
         */
        Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
            if (closeArray === void 0) { closeArray = false; }
            if (updatable === void 0) { updatable = false; }
            return BABYLON.MeshBuilder.CreateRibbon(name, {
                pathArray: pathArray,
                closeArray: closeArray,
                closePath: closePath,
                offset: offset,
                updatable: updatable,
                sideOrientation: sideOrientation,
                instance: instance
            }, scene);
        };
        /**
          * Creates a plane polygonal mesh.  By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
          * @param name defines the name of the mesh to create
          * @param radius sets the radius size (float) of the polygon (default 0.5)
          * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
          * @param scene defines the hosting scene
          * @param updatable defines if the mesh must be flagged as updatable
          * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
          * @returns a new Mesh
          */
        Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
            if (scene === void 0) { scene = null; }
            var options = {
                radius: radius,
                tessellation: tessellation,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
        };
        /**
         * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param size sets the size (float) of each box side (default 1)
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
            if (scene === void 0) { scene = null; }
            var options = {
                size: size,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateBox(name, options, scene);
        };
        /**
          * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
          * @param name defines the name of the mesh to create
          * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
          * @param diameter sets the diameter size (float) of the sphere (default 1)
          * @param scene defines the hosting scene
          * @param updatable defines if the mesh must be flagged as updatable
          * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
          * @returns a new Mesh
          */
        Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
            var options = {
                segments: segments,
                diameterX: diameter,
                diameterY: diameter,
                diameterZ: diameter,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
        };
        /**
         * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param height sets the height size (float) of the cylinder/cone (float, default 2)
         * @param diameterTop set the top cap diameter (floats, default 1)
         * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
         * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
         * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
            if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
                if (scene !== undefined) {
                    sideOrientation = updatable || Mesh.DEFAULTSIDE;
                    updatable = scene;
                }
                scene = subdivisions;
                subdivisions = 1;
            }
            var options = {
                height: height,
                diameterTop: diameterTop,
                diameterBottom: diameterBottom,
                tessellation: tessellation,
                subdivisions: subdivisions,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
        };
        // Torus  (Code from SharpDX.org)
        /**
         * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param diameter sets the diameter size (float) of the torus (default 1)
         * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
         * @param tessellation sets the number of torus sides (postive integer, default 16)
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
            var options = {
                diameter: diameter,
                thickness: thickness,
                tessellation: tessellation,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
        };
        /**
         * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param radius sets the global radius size (float) of the torus knot (default 2)
         * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
         * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
         * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
         * @param p the number of windings on X axis (positive integers, default 2)
         * @param q the number of windings on Y axis (positive integers, default 3)
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
            var options = {
                radius: radius,
                tube: tube,
                radialSegments: radialSegments,
                tubularSegments: tubularSegments,
                p: p,
                q: q,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
        };
        /**
         * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
         * @param name defines the name of the mesh to create
         * @param points is an array successive Vector3
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
         * @returns a new Mesh
         */
        Mesh.CreateLines = function (name, points, scene, updatable, instance) {
            if (scene === void 0) { scene = null; }
            if (updatable === void 0) { updatable = false; }
            if (instance === void 0) { instance = null; }
            var options = {
                points: points,
                updatable: updatable,
                instance: instance
            };
            return BABYLON.MeshBuilder.CreateLines(name, options, scene);
        };
        /**
         * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param points is an array successive Vector3
         * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
         * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
         * @param dashNb is the intended total number of dashes (positive integer, default 200)
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
         * @returns a new Mesh
         */
        Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
            if (scene === void 0) { scene = null; }
            var options = {
                points: points,
                dashSize: dashSize,
                gapSize: gapSize,
                dashNb: dashNb,
                updatable: updatable,
                instance: instance
            };
            return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
        };
        /**
         * Creates a polygon mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
         * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
         * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * Remember you can only change the shape positions, not their number when updating a polygon.
         */
        /**
         * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
         * @param name defines the name of the mesh to create
         * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
         * @param scene defines the hosting scene
         * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
            var options = {
                shape: shape,
                holes: holes,
                updatable: updatable,
                sideOrientation: sideOrientation
            };
            return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
        };
        /**
         * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
         * @param name defines the name of the mesh to create
         * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
         * @param depth defines the height of extrusion
         * @param scene defines the hosting scene
         * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
            var options = {
                shape: shape,
                holes: holes,
                depth: depth,
                updatable: updatable,
                sideOrientation: sideOrientation
            };
            return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
        };
        /**
         * Creates an extruded shape mesh.
         * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
         * @see http://doc.babylonjs.com/how_to/parametric_shapes
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
         * @param name defines the name of the mesh to create
         * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
         * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
         * @param scale is the value to scale the shape
         * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
         * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
         * @returns a new Mesh
         */
        Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
            if (scene === void 0) { scene = null; }
            var options = {
                shape: shape,
                path: path,
                scale: scale,
                rotation: rotation,
                cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
                sideOrientation: sideOrientation,
                instance: instance,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
        };
        /**
         * Creates an custom extruded shape mesh.
         * The custom extrusion is a parametric shape.
         * It has no predefined shape. Its final shape will depend on the input parameters.
         * Please consider using the same method from the MeshBuilder class instead
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
         * @param name defines the name of the mesh to create
         * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
         * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
         * @param scaleFunction is a custom Javascript function called on each path point
         * @param rotationFunction is a custom Javascript function called on each path point
         * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
         * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
         * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
         * @returns a new Mesh
         */
        Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
            var options = {
                shape: shape,
                path: path,
                scaleFunction: scaleFunction,
                rotationFunction: rotationFunction,
                ribbonCloseArray: ribbonCloseArray,
                ribbonClosePath: ribbonClosePath,
                cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
                sideOrientation: sideOrientation,
                instance: instance,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
        };
        /**
         * Creates lathe mesh.
         * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
         * Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
         * @param radius is the radius value of the lathe
         * @param tessellation is the side number of the lathe.
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
            var options = {
                shape: shape,
                radius: radius,
                tessellation: tessellation,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
        };
        /**
         * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param size sets the size (float) of both sides of the plane at once (default 1)
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @returns a new Mesh
         */
        Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
            var options = {
                size: size,
                width: size,
                height: size,
                sideOrientation: sideOrientation,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
        };
        /**
         * Creates a ground mesh.
         * Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param width set the width of the ground
         * @param height set the height of the ground
         * @param subdivisions sets the number of subdivisions per side
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @returns a new Mesh
         */
        Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
            var options = {
                width: width,
                height: height,
                subdivisions: subdivisions,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateGround(name, options, scene);
        };
        /**
         * Creates a tiled ground mesh.
         * Please consider using the same method from the MeshBuilder class instead
         * @param name defines the name of the mesh to create
         * @param xmin set the ground minimum X coordinate
         * @param zmin set the ground minimum Y coordinate
         * @param xmax set the ground maximum X coordinate
         * @param zmax set the ground maximum Z coordinate
         * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
         * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @returns a new Mesh
         */
        Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
            var options = {
                xmin: xmin,
                zmin: zmin,
                xmax: xmax,
                zmax: zmax,
                subdivisions: subdivisions,
                precision: precision,
                updatable: updatable
            };
            return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
        };
        /**
         * Creates a ground mesh from a height map.
         * Please consider using the same method from the MeshBuilder class instead
         * @see http://doc.babylonjs.com/babylon101/height_map
         * @param name defines the name of the mesh to create
         * @param url sets the URL of the height map image resource
         * @param width set the ground width size
         * @param height set the ground height size
         * @param subdivisions sets the number of subdivision per side
         * @param minHeight is the minimum altitude on the ground
         * @param maxHeight is the maximum altitude on the ground
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param onReady  is a callback function that will be called  once the mesh is built (the height map download can last some time)
         * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
         * @returns a new Mesh
         */
        Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
            var options = {
                width: width,
                height: height,
                subdivisions: subdivisions,
                minHeight: minHeight,
                maxHeight: maxHeight,
                updatable: updatable,
                onReady: onReady,
                alphaFilter: alphaFilter
            };
            return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
        };
        /**
         * Creates a tube mesh.
         * The tube is a parametric shape.
         * It has no predefined shape. Its final shape will depend on the input parameters.
         * Please consider using the same method from the MeshBuilder class instead
         * @see http://doc.babylonjs.com/how_to/parametric_shapes
         * @param name defines the name of the mesh to create
         * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
         * @param radius sets the tube radius size
         * @param tessellation is the number of sides on the tubular surface
         * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
         * @param cap sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * @param scene defines the hosting scene
         * @param updatable defines if the mesh must be flagged as updatable
         * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
         * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
         * @returns a new Mesh
         */
        Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
            var options = {
                path: path,
                radius: radius,
                tessellation: tessellation,
                radiusFunction: radiusFunction,
                arc: 1,
                cap: cap,
                updatable: updatable,
                sideOrientation: sideOrientation,
                instance: instance
            };
            return BABYLON.MeshBuilder.CreateTube(name, options, scene);
        };
        /**
          * Creates a polyhedron mesh.
          * Please consider using the same method from the MeshBuilder class instead.
          * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
          * * The parameter `size` (positive float, default 1) sets the polygon size
          * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
          * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
          * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
          * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
          * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
          * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
          * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
          * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
          * @param name defines the name of the mesh to create
          * @param options defines the options used to create the mesh
          * @param scene defines the hosting scene
          * @returns a new Mesh
          */
        Mesh.CreatePolyhedron = function (name, options, scene) {
            return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
        };
        /**
         * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
         * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
         * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)
         * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
         * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns a new Mesh
         * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
         */
        Mesh.CreateIcoSphere = function (name, options, scene) {
            return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
        };
        /**
         * Creates a decal mesh.
         * Please consider using the same method from the MeshBuilder class instead.
         * A decal is a mesh usually applied as a model onto the surface of another mesh
         * @param name  defines the name of the mesh
         * @param sourceMesh defines the mesh receiving the decal
         * @param position sets the position of the decal in world coordinates
         * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
         * @param size sets the decal scaling
         * @param angle sets the angle to rotate the decal
         * @returns a new Mesh
         */
        Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
            var options = {
                position: position,
                normal: normal,
                size: size,
                angle: angle
            };
            return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
        };
        // Skeletons
        /**
         * Prepare internal position array for software CPU skinning
         * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
         */
        Mesh.prototype.setPositionsForCPUSkinning = function () {
            if (!this._sourcePositions) {
                var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                if (!source) {
                    return this._sourcePositions;
                }
                this._sourcePositions = new Float32Array(source);
                if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
                    this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
                }
            }
            return this._sourcePositions;
        };
        /**
         * Prepare internal normal array for software CPU skinning
         * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
         */
        Mesh.prototype.setNormalsForCPUSkinning = function () {
            if (!this._sourceNormals) {
                var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                if (!source) {
                    return this._sourceNormals;
                }
                this._sourceNormals = new Float32Array(source);
                if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
                    this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
                }
            }
            return this._sourceNormals;
        };
        /**
         * Updates the vertex buffer by applying transformation from the bones
         * @param skeleton defines the skeleton to apply to current mesh
         * @returns the current mesh
         */
        Mesh.prototype.applySkeleton = function (skeleton) {
            if (!this.geometry) {
                return this;
            }
            if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
                return this;
            }
            this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                return this;
            }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                return this;
            }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                return this;
            }
            if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                return this;
            }
            if (!this._sourcePositions) {
                var submeshes = this.subMeshes.slice();
                this.setPositionsForCPUSkinning();
                this.subMeshes = submeshes;
            }
            if (!this._sourceNormals) {
                this.setNormalsForCPUSkinning();
            }
            // positionsData checks for not being Float32Array will only pass at most once
            var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!positionsData) {
                return this;
            }
            if (!(positionsData instanceof Float32Array)) {
                positionsData = new Float32Array(positionsData);
            }
            // normalsData checks for not being Float32Array will only pass at most once
            var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            if (!normalsData) {
                return this;
            }
            if (!(normalsData instanceof Float32Array)) {
                normalsData = new Float32Array(normalsData);
            }
            var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
            var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
            if (!matricesWeightsData || !matricesIndicesData) {
                return this;
            }
            var needExtras = this.numBoneInfluencers > 4;
            var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
            var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
            var skeletonMatrices = skeleton.getTransformMatrices(this);
            var tempVector3 = BABYLON.Vector3.Zero();
            var finalMatrix = new BABYLON.Matrix();
            var tempMatrix = new BABYLON.Matrix();
            var matWeightIdx = 0;
            var inf;
            for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
                var weight;
                for (inf = 0; inf < 4; inf++) {
                    weight = matricesWeightsData[matWeightIdx + inf];
                    if (weight > 0) {
                        BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
                        finalMatrix.addToSelf(tempMatrix);
                    }
                }
                if (needExtras) {
                    for (inf = 0; inf < 4; inf++) {
                        weight = matricesWeightsExtraData[matWeightIdx + inf];
                        if (weight > 0) {
                            BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
                            finalMatrix.addToSelf(tempMatrix);
                        }
                    }
                }
                BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
                tempVector3.toArray(positionsData, index);
                BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
                tempVector3.toArray(normalsData, index);
                finalMatrix.reset();
            }
            this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
            this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
            return this;
        };
        // Tools
        /**
         * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
         * @param meshes defines the list of meshes to scan
         * @returns an object `{min:` Vector3`, max:` Vector3`}`
         */
        Mesh.MinMax = function (meshes) {
            var minVector = null;
            var maxVector = null;
            meshes.forEach(function (mesh, index, array) {
                var boundingInfo = mesh.getBoundingInfo();
                var boundingBox = boundingInfo.boundingBox;
                if (!minVector || !maxVector) {
                    minVector = boundingBox.minimumWorld;
                    maxVector = boundingBox.maximumWorld;
                }
                else {
                    minVector.minimizeInPlace(boundingBox.minimumWorld);
                    maxVector.maximizeInPlace(boundingBox.maximumWorld);
                }
            });
            if (!minVector || !maxVector) {
                return {
                    min: BABYLON.Vector3.Zero(),
                    max: BABYLON.Vector3.Zero()
                };
            }
            return {
                min: minVector,
                max: maxVector
            };
        };
        /**
         * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
         * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
         * @returns a vector3
         */
        Mesh.Center = function (meshesOrMinMaxVector) {
            var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
            return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
        };
        /**
         * Merge the array of meshes into a single mesh for performance reasons.
         * @param meshes defines he vertices source.  They should all be of the same material.  Entries can empty
         * @param disposeSource when true (default), dispose of the vertices from the source meshes
         * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
         * @param meshSubclass when set, vertices inserted into this Mesh.  Meshes can then be merged into a Mesh sub-class.
         * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
         * @returns a new mesh
         */
        Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
            if (disposeSource === void 0) { disposeSource = true; }
            var index;
            if (!allow32BitsIndices) {
                var totalVertices = 0;
                // Counting vertices
                for (index = 0; index < meshes.length; index++) {
                    if (meshes[index]) {
                        totalVertices += meshes[index].getTotalVertices();
                        if (totalVertices > 65536) {
                            BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
                            return null;
                        }
                    }
                }
            }
            // Merge
            var vertexData = null;
            var otherVertexData;
            var indiceArray = new Array();
            var source = null;
            for (index = 0; index < meshes.length; index++) {
                if (meshes[index]) {
                    var wm = meshes[index].computeWorldMatrix(true);
                    otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
                    otherVertexData.transform(wm);
                    if (vertexData) {
                        vertexData.merge(otherVertexData, allow32BitsIndices);
                    }
                    else {
                        vertexData = otherVertexData;
                        source = meshes[index];
                    }
                    if (subdivideWithSubMeshes) {
                        indiceArray.push(meshes[index].getTotalIndices());
                    }
                }
            }
            source = source;
            if (!meshSubclass) {
                meshSubclass = new Mesh(source.name + "_merged", source.getScene());
            }
            vertexData.applyToMesh(meshSubclass);
            // Setting properties
            meshSubclass.material = source.material;
            meshSubclass.checkCollisions = source.checkCollisions;
            // Cleaning
            if (disposeSource) {
                for (index = 0; index < meshes.length; index++) {
                    if (meshes[index]) {
                        meshes[index].dispose();
                    }
                }
            }
            // Subdivide
            if (subdivideWithSubMeshes) {
                //-- removal of global submesh
                meshSubclass.releaseSubMeshes();
                index = 0;
                var offset = 0;
                //-- apply subdivision according to index table
                while (index < indiceArray.length) {
                    BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
                    offset += indiceArray[index];
                    index++;
                }
            }
            return meshSubclass;
        };
        // Consts
        /**
         * Mesh side orientation : usually the external or front surface
         */
        Mesh.FRONTSIDE = 0;
        /**
         * Mesh side orientation : usually the internal or back surface
         */
        Mesh.BACKSIDE = 1;
        /**
         * Mesh side orientation : both internal and external or front and back surfaces
         */
        Mesh.DOUBLESIDE = 2;
        /**
         * Mesh side orientation : by default, `FRONTSIDE`
         */
        Mesh.DEFAULTSIDE = 0;
        /**
         * Mesh cap setting : no cap
         */
        Mesh.NO_CAP = 0;
        /**
         * Mesh cap setting : one cap at the beginning of the mesh
         */
        Mesh.CAP_START = 1;
        /**
         * Mesh cap setting : one cap at the end of the mesh
         */
        Mesh.CAP_END = 2;
        /**
         * Mesh cap setting : two caps, one at the beginning  and one at the end of the mesh
         */
        Mesh.CAP_ALL = 3;
        return Mesh;
    }(BABYLON.AbstractMesh));
    BABYLON.Mesh = Mesh;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.mesh.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Base class for submeshes
     */
    var BaseSubMesh = /** @class */ (function () {
        function BaseSubMesh() {
        }
        Object.defineProperty(BaseSubMesh.prototype, "effect", {
            /**
             * Gets associated effect
             */
            get: function () {
                return this._materialEffect;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Sets associated effect (effect used to render this submesh)
         * @param effect defines the effect to associate with
         * @param defines defines the set of defines used to compile this effect
         */
        BaseSubMesh.prototype.setEffect = function (effect, defines) {
            if (defines === void 0) { defines = null; }
            if (this._materialEffect === effect) {
                if (!effect) {
                    this._materialDefines = null;
                }
                return;
            }
            this._materialDefines = defines;
            this._materialEffect = effect;
        };
        return BaseSubMesh;
    }());
    BABYLON.BaseSubMesh = BaseSubMesh;
    /**
     * Defines a subdivision inside a mesh
     */
    var SubMesh = /** @class */ (function (_super) {
        __extends(SubMesh, _super);
        /**
         * Creates a new submesh
         * @param materialIndex defines the material index to use
         * @param verticesStart defines vertex index start
         * @param verticesCount defines vertices count
         * @param indexStart defines index start
         * @param indexCount defines indices count
         * @param mesh defines the parent mesh
         * @param renderingMesh defines an optional rendering mesh
         * @param createBoundingBox defines if bounding box should be created for this submesh
         */
        function SubMesh(
        /** the material index to use */
        materialIndex, 
        /** vertex index start */
        verticesStart, 
        /** vertices count */
        verticesCount, 
        /** index start */
        indexStart, 
        /** indices count */
        indexCount, mesh, renderingMesh, createBoundingBox) {
            if (createBoundingBox === void 0) { createBoundingBox = true; }
            var _this = _super.call(this) || this;
            _this.materialIndex = materialIndex;
            _this.verticesStart = verticesStart;
            _this.verticesCount = verticesCount;
            _this.indexStart = indexStart;
            _this.indexCount = indexCount;
            /** @hidden */
            _this._renderId = 0;
            _this._mesh = mesh;
            _this._renderingMesh = renderingMesh || mesh;
            mesh.subMeshes.push(_this);
            _this._trianglePlanes = [];
            _this._id = mesh.subMeshes.length - 1;
            if (createBoundingBox) {
                _this.refreshBoundingInfo();
                mesh.computeWorldMatrix(true);
            }
            return _this;
        }
        /**
         * Add a new submesh to a mesh
         * @param materialIndex defines the material index to use
         * @param verticesStart defines vertex index start
         * @param verticesCount defines vertices count
         * @param indexStart defines index start
         * @param indexCount defines indices count
         * @param mesh defines the parent mesh
         * @param renderingMesh defines an optional rendering mesh
         * @param createBoundingBox defines if bounding box should be created for this submesh
         * @returns the new submesh
         */
        SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
            if (createBoundingBox === void 0) { createBoundingBox = true; }
            return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
        };
        Object.defineProperty(SubMesh.prototype, "IsGlobal", {
            /**
             * Returns true if this submesh covers the entire parent mesh
             * @ignorenaming
             */
            get: function () {
                return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the submesh BoudingInfo object
         * @returns current bounding info (or mesh's one if the submesh is global)
         */
        SubMesh.prototype.getBoundingInfo = function () {
            if (this.IsGlobal) {
                return this._mesh.getBoundingInfo();
            }
            return this._boundingInfo;
        };
        /**
         * Sets the submesh BoundingInfo
         * @param boundingInfo defines the new bounding info to use
         * @returns the SubMesh
         */
        SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
            this._boundingInfo = boundingInfo;
            return this;
        };
        /**
         * Returns the mesh of the current submesh
         * @return the parent mesh
         */
        SubMesh.prototype.getMesh = function () {
            return this._mesh;
        };
        /**
         * Returns the rendering mesh of the submesh
         * @returns the rendering mesh (could be different from parent mesh)
         */
        SubMesh.prototype.getRenderingMesh = function () {
            return this._renderingMesh;
        };
        /**
         * Returns the submesh material
         * @returns null or the current material
         */
        SubMesh.prototype.getMaterial = function () {
            var rootMaterial = this._renderingMesh.material;
            if (rootMaterial === null || rootMaterial === undefined) {
                return this._mesh.getScene().defaultMaterial;
            }
            else if (rootMaterial.getSubMaterial) {
                var multiMaterial = rootMaterial;
                var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
                if (this._currentMaterial !== effectiveMaterial) {
                    this._currentMaterial = effectiveMaterial;
                    this._materialDefines = null;
                }
                return effectiveMaterial;
            }
            return rootMaterial;
        };
        // Methods
        /**
         * Sets a new updated BoundingInfo object to the submesh
         * @returns the SubMesh
         */
        SubMesh.prototype.refreshBoundingInfo = function () {
            this._lastColliderWorldVertices = null;
            if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
                return this;
            }
            var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!data) {
                this._boundingInfo = this._mesh.getBoundingInfo();
                return this;
            }
            var indices = this._renderingMesh.getIndices();
            var extend;
            //is this the only submesh?
            if (this.indexStart === 0 && this.indexCount === indices.length) {
                var boundingInfo = this._renderingMesh.getBoundingInfo();
                //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
                extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
            }
            else {
                extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
            }
            this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
            return this;
        };
        /** @hidden */
        SubMesh.prototype._checkCollision = function (collider) {
            var boundingInfo = this.getBoundingInfo();
            return boundingInfo._checkCollision(collider);
        };
        /**
         * Updates the submesh BoundingInfo
         * @param world defines the world matrix to use to update the bounding info
         * @returns the submesh
         */
        SubMesh.prototype.updateBoundingInfo = function (world) {
            var boundingInfo = this.getBoundingInfo();
            if (!boundingInfo) {
                this.refreshBoundingInfo();
                boundingInfo = this.getBoundingInfo();
            }
            boundingInfo.update(world);
            return this;
        };
        /**
         * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
         * @param frustumPlanes defines the frustum planes
         * @returns true if the submesh is intersecting with the frustum
         */
        SubMesh.prototype.isInFrustum = function (frustumPlanes) {
            var boundingInfo = this.getBoundingInfo();
            if (!boundingInfo) {
                return false;
            }
            return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
        };
        /**
         * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
         * @param frustumPlanes defines the frustum planes
         * @returns true if the submesh is inside the frustum
         */
        SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
            var boundingInfo = this.getBoundingInfo();
            if (!boundingInfo) {
                return false;
            }
            return boundingInfo.isCompletelyInFrustum(frustumPlanes);
        };
        /**
         * Renders the submesh
         * @param enableAlphaMode defines if alpha needs to be used
         * @returns the submesh
         */
        SubMesh.prototype.render = function (enableAlphaMode) {
            this._renderingMesh.render(this, enableAlphaMode);
            return this;
        };
        /**
         * @hidden
         */
        SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
            if (!this._linesIndexBuffer) {
                var linesIndices = [];
                for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
                    linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
                }
                this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
                this._linesIndexCount = linesIndices.length;
            }
            return this._linesIndexBuffer;
        };
        /**
         * Checks if the submesh intersects with a ray
         * @param ray defines the ray to test
         * @returns true is the passed ray intersects the submesh bounding box
         */
        SubMesh.prototype.canIntersects = function (ray) {
            var boundingInfo = this.getBoundingInfo();
            if (!boundingInfo) {
                return false;
            }
            return ray.intersectsBox(boundingInfo.boundingBox);
        };
        /**
         * Intersects current submesh with a ray
         * @param ray defines the ray to test
         * @param positions defines mesh's positions array
         * @param indices defines mesh's indices array
         * @param fastCheck defines if only bounding info should be used
         * @returns intersection info or null if no intersection
         */
        SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
            var material = this.getMaterial();
            if (!material) {
                return null;
            }
            switch (material.fillMode) {
                case BABYLON.Material.PointListDrawMode:
                case BABYLON.Material.LineListDrawMode:
                case BABYLON.Material.LineLoopDrawMode:
                case BABYLON.Material.LineStripDrawMode:
                case BABYLON.Material.TriangleFanDrawMode:
                case BABYLON.Material.TriangleStripDrawMode:
                    return null;
            }
            // LineMesh first as it's also a Mesh...
            if (BABYLON.LinesMesh) {
                var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
                if (mesh instanceof BABYLON.LinesMesh) {
                    var linesMesh = mesh;
                    return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
                }
            }
            return this._intersectTriangles(ray, positions, indices, fastCheck);
        };
        /** @hidden */
        SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
            var intersectInfo = null;
            // Line test
            for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
                var p0 = positions[indices[index]];
                var p1 = positions[indices[index + 1]];
                var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
                if (length < 0) {
                    continue;
                }
                if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
                    intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
                    if (fastCheck) {
                        break;
                    }
                }
            }
            return intersectInfo;
        };
        /** @hidden */
        SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
            var intersectInfo = null;
            // Triangles test
            for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
                var p0 = positions[indices[index]];
                var p1 = positions[indices[index + 1]];
                var p2 = positions[indices[index + 2]];
                var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
                if (currentIntersectInfo) {
                    if (currentIntersectInfo.distance < 0) {
                        continue;
                    }
                    if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
                        intersectInfo = currentIntersectInfo;
                        intersectInfo.faceId = index / 3;
                        if (fastCheck) {
                            break;
                        }
                    }
                }
            }
            return intersectInfo;
        };
        /** @hidden */
        SubMesh.prototype._rebuild = function () {
            if (this._linesIndexBuffer) {
                this._linesIndexBuffer = null;
            }
        };
        // Clone
        /**
         * Creates a new submesh from the passed mesh
         * @param newMesh defines the new hosting mesh
         * @param newRenderingMesh defines an optional rendering mesh
         * @returns the new submesh
         */
        SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
            var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
            if (!this.IsGlobal) {
                var boundingInfo = this.getBoundingInfo();
                if (!boundingInfo) {
                    return result;
                }
                result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
            }
            return result;
        };
        // Dispose
        /**
         * Release associated resources
         */
        SubMesh.prototype.dispose = function () {
            if (this._linesIndexBuffer) {
                this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
                this._linesIndexBuffer = null;
            }
            // Remove from mesh
            var index = this._mesh.subMeshes.indexOf(this);
            this._mesh.subMeshes.splice(index, 1);
        };
        // Statics
        /**
         * Creates a new submesh from indices data
         * @param materialIndex the index of the main mesh material
         * @param startIndex the index where to start the copy in the mesh indices array
         * @param indexCount the number of indices to copy then from the startIndex
         * @param mesh the main mesh to create the submesh from
         * @param renderingMesh the optional rendering mesh
         * @returns a new submesh
         */
        SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
            var minVertexIndex = Number.MAX_VALUE;
            var maxVertexIndex = -Number.MAX_VALUE;
            renderingMesh = (renderingMesh || mesh);
            var indices = renderingMesh.getIndices();
            for (var index = startIndex; index < startIndex + indexCount; index++) {
                var vertexIndex = indices[index];
                if (vertexIndex < minVertexIndex) {
                    minVertexIndex = vertexIndex;
                }
                if (vertexIndex > maxVertexIndex) {
                    maxVertexIndex = vertexIndex;
                }
            }
            return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
        };
        return SubMesh;
    }(BaseSubMesh));
    BABYLON.SubMesh = SubMesh;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.subMesh.js.map

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};

var BABYLON;
(function (BABYLON) {
    /**
     * Manages the defines for the Material
     */
    var MaterialDefines = /** @class */ (function () {
        function MaterialDefines() {
            this._isDirty = true;
            /** @hidden */
            this._areLightsDirty = true;
            /** @hidden */
            this._areAttributesDirty = true;
            /** @hidden */
            this._areTexturesDirty = true;
            /** @hidden */
            this._areFresnelDirty = true;
            /** @hidden */
            this._areMiscDirty = true;
            /** @hidden */
            this._areImageProcessingDirty = true;
            /** @hidden */
            this._normals = false;
            /** @hidden */
            this._uvs = false;
            /** @hidden */
            this._needNormals = false;
            /** @hidden */
            this._needUVs = false;
        }
        Object.defineProperty(MaterialDefines.prototype, "isDirty", {
            /**
             * Specifies if the material needs to be re-calculated
             */
            get: function () {
                return this._isDirty;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Marks the material to indicate that it has been re-calculated
         */
        MaterialDefines.prototype.markAsProcessed = function () {
            this._isDirty = false;
            this._areAttributesDirty = false;
            this._areTexturesDirty = false;
            this._areFresnelDirty = false;
            this._areLightsDirty = false;
            this._areMiscDirty = false;
            this._areImageProcessingDirty = false;
        };
        /**
         * Marks the material to indicate that it needs to be re-calculated
         */
        MaterialDefines.prototype.markAsUnprocessed = function () {
            this._isDirty = true;
        };
        /**
         * Marks the material to indicate all of its defines need to be re-calculated
         */
        MaterialDefines.prototype.markAllAsDirty = function () {
            this._areTexturesDirty = true;
            this._areAttributesDirty = true;
            this._areLightsDirty = true;
            this._areFresnelDirty = true;
            this._areMiscDirty = true;
            this._areImageProcessingDirty = true;
            this._isDirty = true;
        };
        /**
         * Marks the material to indicate that image processing needs to be re-calculated
         */
        MaterialDefines.prototype.markAsImageProcessingDirty = function () {
            this._areImageProcessingDirty = true;
            this._isDirty = true;
        };
        /**
         * Marks the material to indicate the lights need to be re-calculated
         */
        MaterialDefines.prototype.markAsLightDirty = function () {
            this._areLightsDirty = true;
            this._isDirty = true;
        };
        /**
         * Marks the attribute state as changed
         */
        MaterialDefines.prototype.markAsAttributesDirty = function () {
            this._areAttributesDirty = true;
            this._isDirty = true;
        };
        /**
         * Marks the texture state as changed
         */
        MaterialDefines.prototype.markAsTexturesDirty = function () {
            this._areTexturesDirty = true;
            this._isDirty = true;
        };
        /**
         * Marks the fresnel state as changed
         */
        MaterialDefines.prototype.markAsFresnelDirty = function () {
            this._areFresnelDirty = true;
            this._isDirty = true;
        };
        /**
         * Marks the misc state as changed
         */
        MaterialDefines.prototype.markAsMiscDirty = function () {
            this._areMiscDirty = true;
            this._isDirty = true;
        };
        /**
         * Rebuilds the material defines
         */
        MaterialDefines.prototype.rebuild = function () {
            if (this._keys) {
                delete this._keys;
            }
            this._keys = [];
            for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
                var key = _a[_i];
                if (key[0] === "_") {
                    continue;
                }
                this._keys.push(key);
            }
        };
        /**
         * Specifies if two material defines are equal
         * @param other - A material define instance to compare to
         * @returns - Boolean indicating if the material defines are equal (true) or not (false)
         */
        MaterialDefines.prototype.isEqual = function (other) {
            if (this._keys.length !== other._keys.length) {
                return false;
            }
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                if (this[prop] !== other[prop]) {
                    return false;
                }
            }
            return true;
        };
        /**
         * Clones this instance's defines to another instance
         * @param other - material defines to clone values to
         */
        MaterialDefines.prototype.cloneTo = function (other) {
            if (this._keys.length !== other._keys.length) {
                other._keys = this._keys.slice(0);
            }
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                other[prop] = this[prop];
            }
        };
        /**
         * Resets the material define values
         */
        MaterialDefines.prototype.reset = function () {
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                var type = typeof this[prop];
                switch (type) {
                    case "number":
                        this[prop] = 0;
                        break;
                    case "string":
                        this[prop] = "";
                        break;
                    default:
                        this[prop] = false;
                        break;
                }
            }
        };
        /**
         * Converts the material define values to a string
         * @returns - String of material define information
         */
        MaterialDefines.prototype.toString = function () {
            var result = "";
            for (var index = 0; index < this._keys.length; index++) {
                var prop = this._keys[index];
                var value = this[prop];
                var type = typeof value;
                switch (type) {
                    case "number":
                    case "string":
                        result += "#define " + prop + " " + value + "\n";
                        break;
                    default:
                        if (value) {
                            result += "#define " + prop + "\n";
                        }
                        break;
                }
            }
            return result;
        };
        return MaterialDefines;
    }());
    BABYLON.MaterialDefines = MaterialDefines;
    /**
     * Base class for the main features of a material in Babylon.js
     */
    var Material = /** @class */ (function () {
        /**
         * Creates a material instance
         * @param name defines the name of the material
         * @param scene defines the scene to reference
         * @param doNotAdd specifies if the material should be added to the scene
         */
        function Material(name, scene, doNotAdd) {
            /**
             * Specifies if the ready state should be checked on each call
             */
            this.checkReadyOnEveryCall = false;
            /**
             * Specifies if the ready state should be checked once
             */
            this.checkReadyOnlyOnce = false;
            /**
             * The state of the material
             */
            this.state = "";
            /**
             * The alpha value of the material
             */
            this._alpha = 1.0;
            /**
             * Specifies if back face culling is enabled
             */
            this._backFaceCulling = true;
            /**
             * Specifies if the material should be serialized
             */
            this.doNotSerialize = false;
            /**
             * Specifies if the effect should be stored on sub meshes
             */
            this.storeEffectOnSubMeshes = false;
            /**
            * An event triggered when the material is disposed
            */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
             * Stores the value of the alpha mode
             */
            this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
            /**
             * Stores the state of the need depth pre-pass value
             */
            this._needDepthPrePass = false;
            /**
             * Specifies if depth writing should be disabled
             */
            this.disableDepthWrite = false;
            /**
             * Specifies if depth writing should be forced
             */
            this.forceDepthWrite = false;
            /**
             * Specifies if there should be a separate pass for culling
             */
            this.separateCullingPass = false;
            /**
             * Stores the state specifing if fog should be enabled
             */
            this._fogEnabled = true;
            /**
             * Stores the size of points
             */
            this.pointSize = 1.0;
            /**
             * Stores the z offset value
             */
            this.zOffset = 0;
            /**
             * @hidden
             * Specifies if the material was previously ready
             */
            this._wasPreviouslyReady = false;
            /**
             * Stores the fill mode state
             */
            this._fillMode = Material.TriangleFillMode;
            this.name = name;
            this.id = name || BABYLON.Tools.RandomId();
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            this.uniqueId = this._scene.getUniqueId();
            if (this._scene.useRightHandedSystem) {
                this.sideOrientation = Material.ClockWiseSideOrientation;
            }
            else {
                this.sideOrientation = Material.CounterClockWiseSideOrientation;
            }
            this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
            this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
            if (!doNotAdd) {
                this._scene.materials.push(this);
                this._scene.onNewMaterialAddedObservable.notifyObservers(this);
            }
        }
        Object.defineProperty(Material, "TriangleFillMode", {
            /**
             * Returns the triangle fill mode
             */
            get: function () {
                return Material._TriangleFillMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "WireFrameFillMode", {
            /**
             * Returns the wireframe mode
             */
            get: function () {
                return Material._WireFrameFillMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "PointFillMode", {
            /**
             * Returns the point fill mode
             */
            get: function () {
                return Material._PointFillMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "PointListDrawMode", {
            /**
             * Returns the point list draw mode
             */
            get: function () {
                return Material._PointListDrawMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "LineListDrawMode", {
            /**
             * Returns the line list draw mode
             */
            get: function () {
                return Material._LineListDrawMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "LineLoopDrawMode", {
            /**
             * Returns the line loop draw mode
             */
            get: function () {
                return Material._LineLoopDrawMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "LineStripDrawMode", {
            /**
             * Returns the line strip draw mode
             */
            get: function () {
                return Material._LineStripDrawMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "TriangleStripDrawMode", {
            /**
             * Returns the triangle strip draw mode
             */
            get: function () {
                return Material._TriangleStripDrawMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "TriangleFanDrawMode", {
            /**
             * Returns the triangle fan draw mode
             */
            get: function () {
                return Material._TriangleFanDrawMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "ClockWiseSideOrientation", {
            /**
             * Returns the clock-wise side orientation
             */
            get: function () {
                return Material._ClockWiseSideOrientation;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
            /**
             * Returns the counter clock-wise side orientation
             */
            get: function () {
                return Material._CounterClockWiseSideOrientation;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "alpha", {
            /**
             * Gets the alpha value of the material
             */
            get: function () {
                return this._alpha;
            },
            /**
             * Sets the alpha value of the material
             */
            set: function (value) {
                if (this._alpha === value) {
                    return;
                }
                this._alpha = value;
                this.markAsDirty(Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "backFaceCulling", {
            /**
             * Gets the back-face culling state
             */
            get: function () {
                return this._backFaceCulling;
            },
            /**
             * Sets the back-face culling state
             */
            set: function (value) {
                if (this._backFaceCulling === value) {
                    return;
                }
                this._backFaceCulling = value;
                this.markAsDirty(Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
            /**
             * Gets a boolean indicating that current material needs to register RTT
             */
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "onDispose", {
            /**
             * Called during a dispose event
             */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "onBindObservable", {
            /**
            * An event triggered when the material is bound
            */
            get: function () {
                if (!this._onBindObservable) {
                    this._onBindObservable = new BABYLON.Observable();
                }
                return this._onBindObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "onBind", {
            /**
             * Called during a bind event
             */
            set: function (callback) {
                if (this._onBindObserver) {
                    this.onBindObservable.remove(this._onBindObserver);
                }
                this._onBindObserver = this.onBindObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "onUnBindObservable", {
            /**
            * An event triggered when the material is unbound
            */
            get: function () {
                if (!this._onUnBindObservable) {
                    this._onUnBindObservable = new BABYLON.Observable();
                }
                return this._onUnBindObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "alphaMode", {
            /**
             * Gets the value of the alpha mode
             */
            get: function () {
                return this._alphaMode;
            },
            /**
             * Sets the value of the alpha mode.
             *
             * | Value | Type | Description |
             * | --- | --- | --- |
             * | 0 | ALPHA_DISABLE |   |
             * | 1 | ALPHA_ADD |   |
             * | 2 | ALPHA_COMBINE |   |
             * | 3 | ALPHA_SUBTRACT |   |
             * | 4 | ALPHA_MULTIPLY |   |
             * | 5 | ALPHA_MAXIMIZED |   |
             * | 6 | ALPHA_ONEONE |   |
             * | 7 | ALPHA_PREMULTIPLIED |   |
             * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF |   |
             * | 9 | ALPHA_INTERPOLATE |   |
             * | 10 | ALPHA_SCREENMODE |   |
             *
             */
            set: function (value) {
                if (this._alphaMode === value) {
                    return;
                }
                this._alphaMode = value;
                this.markAsDirty(Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "needDepthPrePass", {
            /**
             * Gets the depth pre-pass value
             */
            get: function () {
                return this._needDepthPrePass;
            },
            /**
             * Sets the need depth pre-pass value
             */
            set: function (value) {
                if (this._needDepthPrePass === value) {
                    return;
                }
                this._needDepthPrePass = value;
                if (this._needDepthPrePass) {
                    this.checkReadyOnEveryCall = true;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "fogEnabled", {
            /**
             * Gets the value of the fog enabled state
             */
            get: function () {
                return this._fogEnabled;
            },
            /**
             * Sets the state for enabling fog
             */
            set: function (value) {
                if (this._fogEnabled === value) {
                    return;
                }
                this._fogEnabled = value;
                this.markAsDirty(Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "wireframe", {
            /**
             * Gets a value specifying if wireframe mode is enabled
             */
            get: function () {
                switch (this._fillMode) {
                    case Material.WireFrameFillMode:
                    case Material.LineListDrawMode:
                    case Material.LineLoopDrawMode:
                    case Material.LineStripDrawMode:
                        return true;
                }
                return this._scene.forceWireframe;
            },
            /**
             * Sets the state of wireframe mode
             */
            set: function (value) {
                this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "pointsCloud", {
            /**
             * Gets the value specifying if point clouds are enabled
             */
            get: function () {
                switch (this._fillMode) {
                    case Material.PointFillMode:
                    case Material.PointListDrawMode:
                        return true;
                }
                return this._scene.forcePointsCloud;
            },
            /**
             * Sets the state of point cloud mode
             */
            set: function (value) {
                this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Material.prototype, "fillMode", {
            /**
             * Gets the material fill mode
             */
            get: function () {
                return this._fillMode;
            },
            /**
             * Sets the material fill mode
             */
            set: function (value) {
                if (this._fillMode === value) {
                    return;
                }
                this._fillMode = value;
                this.markAsDirty(Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns a string representation of the current material
         * @param fullDetails defines a boolean indicating which levels of logging is desired
         * @returns a string with material information
         */
        Material.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            if (fullDetails) {
            }
            return ret;
        };
        /**
         * Gets the class name of the material
         * @returns a string with the class name of the material
         */
        Material.prototype.getClassName = function () {
            return "Material";
        };
        Object.defineProperty(Material.prototype, "isFrozen", {
            /**
             * Specifies if updates for the material been locked
             */
            get: function () {
                return this.checkReadyOnlyOnce;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Locks updates for the material
         */
        Material.prototype.freeze = function () {
            this.checkReadyOnlyOnce = true;
        };
        /**
         * Unlocks updates for the material
         */
        Material.prototype.unfreeze = function () {
            this.checkReadyOnlyOnce = false;
        };
        /**
         * Specifies if the material is ready to be used
         * @param mesh defines the mesh to check
         * @param useInstances specifies if instances should be used
         * @returns a boolean indicating if the material is ready to be used
         */
        Material.prototype.isReady = function (mesh, useInstances) {
            return true;
        };
        /**
         * Specifies that the submesh is ready to be used
         * @param mesh defines the mesh to check
         * @param subMesh defines which submesh to check
         * @param useInstances specifies that instances should be used
         * @returns a boolean indicating that the submesh is ready or not
         */
        Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
            return false;
        };
        /**
         * Returns the material effect
         * @returns the effect associated with the material
         */
        Material.prototype.getEffect = function () {
            return this._effect;
        };
        /**
         * Returns the current scene
         * @returns a Scene
         */
        Material.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Specifies if the material will require alpha blending
         * @returns a boolean specifying if alpha blending is needed
         */
        Material.prototype.needAlphaBlending = function () {
            return (this.alpha < 1.0);
        };
        /**
         * Specifies if the mesh will require alpha blending
         * @param mesh defines the mesh to check
         * @returns a boolean specifying if alpha blending is needed for the mesh
         */
        Material.prototype.needAlphaBlendingForMesh = function (mesh) {
            return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
        };
        /**
         * Specifies if this material should be rendered in alpha test mode
         * @returns a boolean specifying if an alpha test is needed.
         */
        Material.prototype.needAlphaTesting = function () {
            return false;
        };
        /**
         * Gets the texture used for the alpha test
         * @returns the texture to use for alpha testing
         */
        Material.prototype.getAlphaTestTexture = function () {
            return null;
        };
        /**
         * Marks the material to indicate that it needs to be re-calculated
         */
        Material.prototype.markDirty = function () {
            this._wasPreviouslyReady = false;
        };
        /** @hidden */
        Material.prototype._preBind = function (effect, overrideOrientation) {
            if (overrideOrientation === void 0) { overrideOrientation = null; }
            var engine = this._scene.getEngine();
            var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
            var reverse = orientation === Material.ClockWiseSideOrientation;
            engine.enableEffect(effect ? effect : this._effect);
            engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
            return reverse;
        };
        /**
         * Binds the material to the mesh
         * @param world defines the world transformation matrix
         * @param mesh defines the mesh to bind the material to
         */
        Material.prototype.bind = function (world, mesh) {
        };
        /**
         * Binds the submesh to the material
         * @param world defines the world transformation matrix
         * @param mesh defines the mesh containing the submesh
         * @param subMesh defines the submesh to bind the material to
         */
        Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
        };
        /**
         * Binds the world matrix to the material
         * @param world defines the world transformation matrix
         */
        Material.prototype.bindOnlyWorldMatrix = function (world) {
        };
        /**
         * Binds the scene's uniform buffer to the effect.
         * @param effect defines the effect to bind to the scene uniform buffer
         * @param sceneUbo defines the uniform buffer storing scene data
         */
        Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
            sceneUbo.bindToEffect(effect, "Scene");
        };
        /**
         * Binds the view matrix to the effect
         * @param effect defines the effect to bind the view matrix to
         */
        Material.prototype.bindView = function (effect) {
            if (!this._useUBO) {
                effect.setMatrix("view", this.getScene().getViewMatrix());
            }
            else {
                this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
            }
        };
        /**
         * Binds the view projection matrix to the effect
         * @param effect defines the effect to bind the view projection matrix to
         */
        Material.prototype.bindViewProjection = function (effect) {
            if (!this._useUBO) {
                effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
            }
            else {
                this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
            }
        };
        /**
         * Specifies if material alpha testing should be turned on for the mesh
         * @param mesh defines the mesh to check
         */
        Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
            return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
        };
        /**
         * Processes to execute after binding the material to a mesh
         * @param mesh defines the rendered mesh
         */
        Material.prototype._afterBind = function (mesh) {
            this._scene._cachedMaterial = this;
            if (mesh) {
                this._scene._cachedVisibility = mesh.visibility;
            }
            else {
                this._scene._cachedVisibility = 1;
            }
            if (this._onBindObservable && mesh) {
                this._onBindObservable.notifyObservers(mesh);
            }
            if (this.disableDepthWrite) {
                var engine = this._scene.getEngine();
                this._cachedDepthWriteState = engine.getDepthWrite();
                engine.setDepthWrite(false);
            }
        };
        /**
         * Unbinds the material from the mesh
         */
        Material.prototype.unbind = function () {
            if (this._onUnBindObservable) {
                this._onUnBindObservable.notifyObservers(this);
            }
            if (this.disableDepthWrite) {
                var engine = this._scene.getEngine();
                engine.setDepthWrite(this._cachedDepthWriteState);
            }
        };
        /**
         * Gets the active textures from the material
         * @returns an array of textures
         */
        Material.prototype.getActiveTextures = function () {
            return [];
        };
        /**
         * Specifies if the material uses a texture
         * @param texture defines the texture to check against the material
         * @returns a boolean specifying if the material uses the texture
         */
        Material.prototype.hasTexture = function (texture) {
            return false;
        };
        /**
         * Makes a duplicate of the material, and gives it a new name
         * @param name defines the new name for the duplicated material
         * @returns the cloned material
         */
        Material.prototype.clone = function (name) {
            return null;
        };
        /**
         * Gets the meshes bound to the material
         * @returns an array of meshes bound to the material
         */
        Material.prototype.getBindedMeshes = function () {
            var result = new Array();
            for (var index = 0; index < this._scene.meshes.length; index++) {
                var mesh = this._scene.meshes[index];
                if (mesh.material === this) {
                    result.push(mesh);
                }
            }
            return result;
        };
        /**
         * Force shader compilation
         * @param mesh defines the mesh associated with this material
         * @param onCompiled defines a function to execute once the material is compiled
         * @param options defines the options to configure the compilation
         */
        Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
            var _this = this;
            var localOptions = __assign({ clipPlane: false }, options);
            var subMesh = new BABYLON.BaseSubMesh();
            var scene = this.getScene();
            var checkReady = function () {
                if (!_this._scene || !_this._scene.getEngine()) {
                    return;
                }
                if (subMesh._materialDefines) {
                    subMesh._materialDefines._renderId = -1;
                }
                var clipPlaneState = scene.clipPlane;
                if (localOptions.clipPlane) {
                    scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
                }
                if (_this.storeEffectOnSubMeshes) {
                    if (_this.isReadyForSubMesh(mesh, subMesh)) {
                        if (onCompiled) {
                            onCompiled(_this);
                        }
                    }
                    else {
                        setTimeout(checkReady, 16);
                    }
                }
                else {
                    if (_this.isReady(mesh)) {
                        if (onCompiled) {
                            onCompiled(_this);
                        }
                    }
                    else {
                        setTimeout(checkReady, 16);
                    }
                }
                if (localOptions.clipPlane) {
                    scene.clipPlane = clipPlaneState;
                }
            };
            checkReady();
        };
        /**
         * Force shader compilation
         * @param mesh defines the mesh that will use this material
         * @param options defines additional options for compiling the shaders
         * @returns a promise that resolves when the compilation completes
         */
        Material.prototype.forceCompilationAsync = function (mesh, options) {
            var _this = this;
            return new Promise(function (resolve) {
                _this.forceCompilation(mesh, function () {
                    resolve();
                }, options);
            });
        };
        /**
         * Marks a define in the material to indicate that it needs to be re-computed
         * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
         */
        Material.prototype.markAsDirty = function (flag) {
            if (flag & Material.TextureDirtyFlag) {
                this._markAllSubMeshesAsTexturesDirty();
            }
            if (flag & Material.LightDirtyFlag) {
                this._markAllSubMeshesAsLightsDirty();
            }
            if (flag & Material.FresnelDirtyFlag) {
                this._markAllSubMeshesAsFresnelDirty();
            }
            if (flag & Material.AttributesDirtyFlag) {
                this._markAllSubMeshesAsAttributesDirty();
            }
            if (flag & Material.MiscDirtyFlag) {
                this._markAllSubMeshesAsMiscDirty();
            }
            this.getScene().resetCachedMaterial();
        };
        /**
         * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
         * @param func defines a function which checks material defines against the submeshes
         */
        Material.prototype._markAllSubMeshesAsDirty = function (func) {
            for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                if (!mesh.subMeshes) {
                    continue;
                }
                for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
                    var subMesh = _c[_b];
                    if (subMesh.getMaterial() !== this) {
                        continue;
                    }
                    if (!subMesh._materialDefines) {
                        continue;
                    }
                    func(subMesh._materialDefines);
                }
            }
        };
        /**
         * Indicates that image processing needs to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
        };
        /**
         * Indicates that textures need to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
        };
        /**
         * Indicates that fresnel needs to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
        };
        /**
         * Indicates that fresnel and misc need to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) {
                defines.markAsFresnelDirty();
                defines.markAsMiscDirty();
            });
        };
        /**
         * Indicates that lights need to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsLightsDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
        };
        /**
         * Indicates that attributes need to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
        };
        /**
         * Indicates that misc needs to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsMiscDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
        };
        /**
         * Indicates that textures and misc need to be re-calculated for all submeshes
         */
        Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
            this._markAllSubMeshesAsDirty(function (defines) {
                defines.markAsTexturesDirty();
                defines.markAsMiscDirty();
            });
        };
        /**
         * Disposes the material
         * @param forceDisposeEffect specifies if effects should be forcefully disposed
         * @param forceDisposeTextures specifies if textures should be forcefully disposed
         */
        Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            // Animations
            this.getScene().stopAnimation(this);
            this.getScene().freeProcessedMaterials();
            // Remove from scene
            var index = this._scene.materials.indexOf(this);
            if (index >= 0) {
                this._scene.materials.splice(index, 1);
            }
            this._scene.onMaterialRemovedObservable.notifyObservers(this);
            // 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;
                    if (mesh.geometry) {
                        var geometry = (mesh.geometry);
                        if (this.storeEffectOnSubMeshes) {
                            for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
                                var subMesh = _a[_i];
                                geometry._releaseVertexArrayObject(subMesh._materialEffect);
                                if (forceDisposeEffect && subMesh._materialEffect) {
                                    this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
                                }
                            }
                        }
                        else {
                            geometry._releaseVertexArrayObject(this._effect);
                        }
                    }
                }
            }
            this._uniformBuffer.dispose();
            // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
            if (forceDisposeEffect && this._effect) {
                if (!this.storeEffectOnSubMeshes) {
                    this._scene.getEngine()._releaseEffect(this._effect);
                }
                this._effect = null;
            }
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            if (this._onBindObservable) {
                this._onBindObservable.clear();
            }
            if (this._onUnBindObservable) {
                this._onUnBindObservable.clear();
            }
        };
        /**
         * Serializes this material
         * @returns the serialized material object
         */
        Material.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        /**
         * Creates a MultiMaterial from parsed MultiMaterial data.
         * @param parsedMultiMaterial defines parsed MultiMaterial data.
         * @param scene defines the hosting scene
         * @returns a new MultiMaterial
         */
        Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
            var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
            multiMaterial.id = parsedMultiMaterial.id;
            if (BABYLON.Tags) {
                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;
        };
        /**
         * Creates a material from parsed material data
         * @param parsedMaterial defines parsed material data
         * @param scene defines the hosting scene
         * @param rootUrl defines the root URL to use to load textures
         * @returns a new material
         */
        Material.Parse = function (parsedMaterial, scene, rootUrl) {
            if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
                return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
            }
            if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
                parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
                if (!BABYLON.LegacyPBRMaterial) {
                    BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
                    return;
                }
            }
            var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
            return materialType.Parse(parsedMaterial, scene, rootUrl);
        };
        // Triangle views
        Material._TriangleFillMode = 0;
        Material._WireFrameFillMode = 1;
        Material._PointFillMode = 2;
        // Draw modes
        Material._PointListDrawMode = 3;
        Material._LineListDrawMode = 4;
        Material._LineLoopDrawMode = 5;
        Material._LineStripDrawMode = 6;
        Material._TriangleStripDrawMode = 7;
        Material._TriangleFanDrawMode = 8;
        /**
         * Stores the clock-wise side orientation
         */
        Material._ClockWiseSideOrientation = 0;
        /**
         * Stores the counter clock-wise side orientation
         */
        Material._CounterClockWiseSideOrientation = 1;
        /**
         * The dirty texture flag value
         */
        Material.TextureDirtyFlag = 1;
        /**
         * The dirty light flag value
         */
        Material.LightDirtyFlag = 2;
        /**
         * The dirty fresnel flag value
         */
        Material.FresnelDirtyFlag = 4;
        /**
         * The dirty attribute flag value
         */
        Material.AttributesDirtyFlag = 8;
        /**
         * The dirty misc flag value
         */
        Material.MiscDirtyFlag = 16;
        /**
         * The all dirty flag value
         */
        Material.AllDirtyFlag = 31;
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "id", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "uniqueId", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "name", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "checkReadyOnEveryCall", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "checkReadyOnlyOnce", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "state", void 0);
        __decorate([
            BABYLON.serialize("alpha")
        ], Material.prototype, "_alpha", void 0);
        __decorate([
            BABYLON.serialize("backFaceCulling")
        ], Material.prototype, "_backFaceCulling", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "sideOrientation", void 0);
        __decorate([
            BABYLON.serialize("alphaMode")
        ], Material.prototype, "_alphaMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "_needDepthPrePass", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "disableDepthWrite", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "forceDepthWrite", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "separateCullingPass", void 0);
        __decorate([
            BABYLON.serialize("fogEnabled")
        ], Material.prototype, "_fogEnabled", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "pointSize", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "zOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "wireframe", null);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "pointsCloud", null);
        __decorate([
            BABYLON.serialize()
        ], Material.prototype, "fillMode", null);
        return Material;
    }());
    BABYLON.Material = Material;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.material.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Uniform buffer objects.
     *
     * Handles blocks of uniform on the GPU.
     *
     * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
     *
     * For more information, please refer to :
     * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
     */
    var UniformBuffer = /** @class */ (function () {
        /**
         * Instantiates a new Uniform buffer objects.
         *
         * Handles blocks of uniform on the GPU.
         *
         * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
         *
         * For more information, please refer to :
         * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
         * @param engine Define the engine the buffer is associated with
         * @param data Define the data contained in the buffer
         * @param dynamic Define if the buffer is updatable
         */
        function UniformBuffer(engine, data, dynamic) {
            this._engine = engine;
            this._noUBO = !engine.supportsUniformBuffers;
            this._dynamic = dynamic;
            this._data = data || [];
            this._uniformLocations = {};
            this._uniformSizes = {};
            this._uniformLocationPointer = 0;
            this._needSync = false;
            if (this._noUBO) {
                this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
                this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
                this.updateFloat = this._updateFloatForEffect;
                this.updateFloat2 = this._updateFloat2ForEffect;
                this.updateFloat3 = this._updateFloat3ForEffect;
                this.updateFloat4 = this._updateFloat4ForEffect;
                this.updateMatrix = this._updateMatrixForEffect;
                this.updateVector3 = this._updateVector3ForEffect;
                this.updateVector4 = this._updateVector4ForEffect;
                this.updateColor3 = this._updateColor3ForEffect;
                this.updateColor4 = this._updateColor4ForEffect;
            }
            else {
                this._engine._uniformBuffers.push(this);
                this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
                this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
                this.updateFloat = this._updateFloatForUniform;
                this.updateFloat2 = this._updateFloat2ForUniform;
                this.updateFloat3 = this._updateFloat3ForUniform;
                this.updateFloat4 = this._updateFloat4ForUniform;
                this.updateMatrix = this._updateMatrixForUniform;
                this.updateVector3 = this._updateVector3ForUniform;
                this.updateVector4 = this._updateVector4ForUniform;
                this.updateColor3 = this._updateColor3ForUniform;
                this.updateColor4 = this._updateColor4ForUniform;
            }
        }
        Object.defineProperty(UniformBuffer.prototype, "useUbo", {
            /**
             * Indicates if the buffer is using the WebGL2 UBO implementation,
             * or just falling back on setUniformXXX calls.
             */
            get: function () {
                return !this._noUBO;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(UniformBuffer.prototype, "isSync", {
            /**
             * Indicates if the WebGL underlying uniform buffer is in sync
             * with the javascript cache data.
             */
            get: function () {
                return !this._needSync;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Indicates if the WebGL underlying uniform buffer is dynamic.
         * Also, a dynamic UniformBuffer will disable cache verification and always
         * update the underlying WebGL uniform buffer to the GPU.
         * @returns if Dynamic, otherwise false
         */
        UniformBuffer.prototype.isDynamic = function () {
            return this._dynamic !== undefined;
        };
        /**
         * The data cache on JS side.
         * @returns the underlying data as a float array
         */
        UniformBuffer.prototype.getData = function () {
            return this._bufferData;
        };
        /**
         * The underlying WebGL Uniform buffer.
         * @returns the webgl buffer
         */
        UniformBuffer.prototype.getBuffer = function () {
            return this._buffer;
        };
        /**
         * std140 layout specifies how to align data within an UBO structure.
         * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
         * for specs.
         */
        UniformBuffer.prototype._fillAlignment = function (size) {
            // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
            // and 4x4 matrices
            // TODO : change if other types are used
            var alignment;
            if (size <= 2) {
                alignment = size;
            }
            else {
                alignment = 4;
            }
            if ((this._uniformLocationPointer % alignment) !== 0) {
                var oldPointer = this._uniformLocationPointer;
                this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
                var diff = this._uniformLocationPointer - oldPointer;
                for (var i = 0; i < diff; i++) {
                    this._data.push(0);
                }
            }
        };
        /**
         * Adds an uniform in the buffer.
         * Warning : the subsequents calls of this function must be in the same order as declared in the shader
         * for the layout to be correct !
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param size Data size, or data directly.
         */
        UniformBuffer.prototype.addUniform = function (name, size) {
            if (this._noUBO) {
                return;
            }
            if (this._uniformLocations[name] !== undefined) {
                // Already existing uniform
                return;
            }
            // This function must be called in the order of the shader layout !
            // size can be the size of the uniform, or data directly
            var data;
            if (size instanceof Array) {
                data = size;
                size = data.length;
            }
            else {
                size = size;
                data = [];
                // Fill with zeros
                for (var i = 0; i < size; i++) {
                    data.push(0);
                }
            }
            this._fillAlignment(size);
            this._uniformSizes[name] = size;
            this._uniformLocations[name] = this._uniformLocationPointer;
            this._uniformLocationPointer += size;
            for (var i = 0; i < size; i++) {
                this._data.push(data[i]);
            }
            this._needSync = true;
        };
        /**
         * Adds a Matrix 4x4 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param mat A 4x4 matrix.
         */
        UniformBuffer.prototype.addMatrix = function (name, mat) {
            this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
        };
        /**
         * Adds a vec2 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param x Define the x component value of the vec2
         * @param y Define the y component value of the vec2
         */
        UniformBuffer.prototype.addFloat2 = function (name, x, y) {
            var temp = [x, y];
            this.addUniform(name, temp);
        };
        /**
         * Adds a vec3 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param x Define the x component value of the vec3
         * @param y Define the y component value of the vec3
         * @param z Define the z component value of the vec3
         */
        UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
            var temp = [x, y, z];
            this.addUniform(name, temp);
        };
        /**
         * Adds a vec3 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param color Define the vec3 from a Color
         */
        UniformBuffer.prototype.addColor3 = function (name, color) {
            var temp = new Array();
            color.toArray(temp);
            this.addUniform(name, temp);
        };
        /**
         * Adds a vec4 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param color Define the rgb components from a Color
         * @param alpha Define the a component of the vec4
         */
        UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
            var temp = new Array();
            color.toArray(temp);
            temp.push(alpha);
            this.addUniform(name, temp);
        };
        /**
         * Adds a vec3 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         * @param vector Define the vec3 components from a Vector
         */
        UniformBuffer.prototype.addVector3 = function (name, vector) {
            var temp = new Array();
            vector.toArray(temp);
            this.addUniform(name, temp);
        };
        /**
         * Adds a Matrix 3x3 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         */
        UniformBuffer.prototype.addMatrix3x3 = function (name) {
            this.addUniform(name, 12);
        };
        /**
         * Adds a Matrix 2x2 to the uniform buffer.
         * @param name Name of the uniform, as used in the uniform block in the shader.
         */
        UniformBuffer.prototype.addMatrix2x2 = function (name) {
            this.addUniform(name, 8);
        };
        /**
         * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
         */
        UniformBuffer.prototype.create = function () {
            if (this._noUBO) {
                return;
            }
            if (this._buffer) {
                return; // nothing to do
            }
            // See spec, alignment must be filled as a vec4
            this._fillAlignment(4);
            this._bufferData = new Float32Array(this._data);
            this._rebuild();
            this._needSync = true;
        };
        /** @hidden */
        UniformBuffer.prototype._rebuild = function () {
            if (this._noUBO) {
                return;
            }
            if (this._dynamic) {
                this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
            }
            else {
                this._buffer = this._engine.createUniformBuffer(this._bufferData);
            }
        };
        /**
         * Updates the WebGL Uniform Buffer on the GPU.
         * If the `dynamic` flag is set to true, no cache comparison is done.
         * Otherwise, the buffer will be updated only if the cache differs.
         */
        UniformBuffer.prototype.update = function () {
            if (!this._buffer) {
                this.create();
                return;
            }
            if (!this._dynamic && !this._needSync) {
                return;
            }
            this._engine.updateUniformBuffer(this._buffer, this._bufferData);
            this._needSync = false;
        };
        /**
         * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
         * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
         * @param data Define the flattened data
         * @param size Define the size of the data.
         */
        UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
            var location = this._uniformLocations[uniformName];
            if (location === undefined) {
                if (this._buffer) {
                    // Cannot add an uniform if the buffer is already created
                    BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
                    return;
                }
                this.addUniform(uniformName, size);
                location = this._uniformLocations[uniformName];
            }
            if (!this._buffer) {
                this.create();
            }
            if (!this._dynamic) {
                // Cache for static uniform buffers
                var changed = false;
                for (var i = 0; i < size; i++) {
                    if (this._bufferData[location + i] !== data[i]) {
                        changed = true;
                        this._bufferData[location + i] = data[i];
                    }
                }
                this._needSync = this._needSync || changed;
            }
            else {
                // No cache for dynamic
                for (var i = 0; i < size; i++) {
                    this._bufferData[location + i] = data[i];
                }
            }
        };
        // Update methods
        UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
            // To match std140, matrix must be realigned
            for (var i = 0; i < 3; i++) {
                UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
                UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
                UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
                UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
            }
            this.updateUniform(name, UniformBuffer._tempBuffer, 12);
        };
        UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
            this._currentEffect.setMatrix3x3(name, matrix);
        };
        UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
            this._currentEffect.setMatrix2x2(name, matrix);
        };
        UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
            // To match std140, matrix must be realigned
            for (var i = 0; i < 2; i++) {
                UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
                UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
                UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
                UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
            }
            this.updateUniform(name, UniformBuffer._tempBuffer, 8);
        };
        UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
            this._currentEffect.setFloat(name, x);
        };
        UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
            UniformBuffer._tempBuffer[0] = x;
            this.updateUniform(name, UniformBuffer._tempBuffer, 1);
        };
        UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
            if (suffix === void 0) { suffix = ""; }
            this._currentEffect.setFloat2(name + suffix, x, y);
        };
        UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
            if (suffix === void 0) { suffix = ""; }
            UniformBuffer._tempBuffer[0] = x;
            UniformBuffer._tempBuffer[1] = y;
            this.updateUniform(name, UniformBuffer._tempBuffer, 2);
        };
        UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
            if (suffix === void 0) { suffix = ""; }
            this._currentEffect.setFloat3(name + suffix, x, y, z);
        };
        UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
            if (suffix === void 0) { suffix = ""; }
            UniformBuffer._tempBuffer[0] = x;
            UniformBuffer._tempBuffer[1] = y;
            UniformBuffer._tempBuffer[2] = z;
            this.updateUniform(name, UniformBuffer._tempBuffer, 3);
        };
        UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
            if (suffix === void 0) { suffix = ""; }
            this._currentEffect.setFloat4(name + suffix, x, y, z, w);
        };
        UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
            if (suffix === void 0) { suffix = ""; }
            UniformBuffer._tempBuffer[0] = x;
            UniformBuffer._tempBuffer[1] = y;
            UniformBuffer._tempBuffer[2] = z;
            UniformBuffer._tempBuffer[3] = w;
            this.updateUniform(name, UniformBuffer._tempBuffer, 4);
        };
        UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
            this._currentEffect.setMatrix(name, mat);
        };
        UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
            this.updateUniform(name, mat.toArray(), 16);
        };
        UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
            this._currentEffect.setVector3(name, vector);
        };
        UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
            vector.toArray(UniformBuffer._tempBuffer);
            this.updateUniform(name, UniformBuffer._tempBuffer, 3);
        };
        UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
            this._currentEffect.setVector4(name, vector);
        };
        UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
            vector.toArray(UniformBuffer._tempBuffer);
            this.updateUniform(name, UniformBuffer._tempBuffer, 4);
        };
        UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
            if (suffix === void 0) { suffix = ""; }
            this._currentEffect.setColor3(name + suffix, color);
        };
        UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
            if (suffix === void 0) { suffix = ""; }
            color.toArray(UniformBuffer._tempBuffer);
            this.updateUniform(name, UniformBuffer._tempBuffer, 3);
        };
        UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
            if (suffix === void 0) { suffix = ""; }
            this._currentEffect.setColor4(name + suffix, color, alpha);
        };
        UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
            if (suffix === void 0) { suffix = ""; }
            color.toArray(UniformBuffer._tempBuffer);
            UniformBuffer._tempBuffer[3] = alpha;
            this.updateUniform(name, UniformBuffer._tempBuffer, 4);
        };
        /**
         * Sets a sampler uniform on the effect.
         * @param name Define the name of the sampler.
         * @param texture Define the texture to set in the sampler
         */
        UniformBuffer.prototype.setTexture = function (name, texture) {
            this._currentEffect.setTexture(name, texture);
        };
        /**
         * Directly updates the value of the uniform in the cache AND on the GPU.
         * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
         * @param data Define the flattened data
         */
        UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
            this.updateUniform(uniformName, data, data.length);
            this.update();
        };
        /**
         * Binds this uniform buffer to an effect.
         * @param effect Define the effect to bind the buffer to
         * @param name Name of the uniform block in the shader.
         */
        UniformBuffer.prototype.bindToEffect = function (effect, name) {
            this._currentEffect = effect;
            if (this._noUBO || !this._buffer) {
                return;
            }
            effect.bindUniformBuffer(this._buffer, name);
        };
        /**
         * Disposes the uniform buffer.
         */
        UniformBuffer.prototype.dispose = function () {
            if (this._noUBO) {
                return;
            }
            var index = this._engine._uniformBuffers.indexOf(this);
            if (index !== -1) {
                this._engine._uniformBuffers.splice(index, 1);
            }
            if (!this._buffer) {
                return;
            }
            if (this._engine._releaseBuffer(this._buffer)) {
                this._buffer = null;
            }
        };
        // Pool for avoiding memory leaks
        UniformBuffer._MAX_UNIFORM_SIZE = 256;
        UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
        return UniformBuffer;
    }());
    BABYLON.UniformBuffer = UniformBuffer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.uniformBuffer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
     */
    var VertexData = /** @class */ (function () {
        function VertexData() {
        }
        /**
         * Uses the passed data array to set the set the values for the specified kind of data
         * @param data a linear array of floating numbers
         * @param kind the type of data that is being set, eg positions, colors etc
         */
        VertexData.prototype.set = function (data, kind) {
            switch (kind) {
                case BABYLON.VertexBuffer.PositionKind:
                    this.positions = data;
                    break;
                case BABYLON.VertexBuffer.NormalKind:
                    this.normals = data;
                    break;
                case BABYLON.VertexBuffer.TangentKind:
                    this.tangents = data;
                    break;
                case BABYLON.VertexBuffer.UVKind:
                    this.uvs = data;
                    break;
                case BABYLON.VertexBuffer.UV2Kind:
                    this.uvs2 = data;
                    break;
                case BABYLON.VertexBuffer.UV3Kind:
                    this.uvs3 = data;
                    break;
                case BABYLON.VertexBuffer.UV4Kind:
                    this.uvs4 = data;
                    break;
                case BABYLON.VertexBuffer.UV5Kind:
                    this.uvs5 = data;
                    break;
                case BABYLON.VertexBuffer.UV6Kind:
                    this.uvs6 = data;
                    break;
                case BABYLON.VertexBuffer.ColorKind:
                    this.colors = data;
                    break;
                case BABYLON.VertexBuffer.MatricesIndicesKind:
                    this.matricesIndices = data;
                    break;
                case BABYLON.VertexBuffer.MatricesWeightsKind:
                    this.matricesWeights = data;
                    break;
                case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
                    this.matricesIndicesExtra = data;
                    break;
                case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
                    this.matricesWeightsExtra = data;
                    break;
            }
        };
        /**
         * Associates the vertexData to the passed Mesh.
         * Sets it as updatable or not (default `false`)
         * @param mesh the mesh the vertexData is applied to
         * @param updatable when used and having the value true allows new data to update the vertexData
         * @returns the VertexData
         */
        VertexData.prototype.applyToMesh = function (mesh, updatable) {
            this._applyTo(mesh, updatable);
            return this;
        };
        /**
         * Associates the vertexData to the passed Geometry.
         * Sets it as updatable or not (default `false`)
         * @param geometry the geometry the vertexData is applied to
         * @param updatable when used and having the value true allows new data to update the vertexData
         * @returns VertexData
         */
        VertexData.prototype.applyToGeometry = function (geometry, updatable) {
            this._applyTo(geometry, updatable);
            return this;
        };
        /**
         * Updates the associated mesh
         * @param mesh the mesh to be updated
         * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
         * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be  created from these positions and set to the mesh, optional with default false
         * @returns VertexData
         */
        VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
            this._update(mesh);
            return this;
        };
        /**
         * Updates the associated geometry
         * @param geometry the geometry to be updated
         * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
         * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
         * @returns VertexData.
         */
        VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
            this._update(geometry);
            return this;
        };
        VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
            if (updatable === void 0) { updatable = false; }
            if (this.positions) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
            }
            if (this.normals) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
            }
            if (this.tangents) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
            }
            if (this.uvs) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
            }
            if (this.uvs2) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
            }
            if (this.uvs3) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
            }
            if (this.uvs4) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
            }
            if (this.uvs5) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
            }
            if (this.uvs6) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
            }
            if (this.colors) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
            }
            if (this.matricesIndices) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
            }
            if (this.matricesWeights) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
            }
            if (this.matricesIndicesExtra) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
            }
            if (this.matricesWeightsExtra) {
                meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
            }
            if (this.indices) {
                meshOrGeometry.setIndices(this.indices, null, updatable);
            }
            else {
                meshOrGeometry.setIndices([], null);
            }
            return this;
        };
        VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
            if (this.positions) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
            }
            if (this.normals) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
            }
            if (this.tangents) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
            }
            if (this.uvs) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
            }
            if (this.uvs2) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
            }
            if (this.uvs3) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
            }
            if (this.uvs4) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
            }
            if (this.uvs5) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
            }
            if (this.uvs6) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
            }
            if (this.colors) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
            }
            if (this.matricesIndices) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
            }
            if (this.matricesWeights) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
            }
            if (this.matricesIndicesExtra) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
            }
            if (this.matricesWeightsExtra) {
                meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
            }
            if (this.indices) {
                meshOrGeometry.setIndices(this.indices, null);
            }
            return this;
        };
        /**
         * Transforms each position and each normal of the vertexData according to the passed Matrix
         * @param matrix the transforming matrix
         * @returns the VertexData
         */
        VertexData.prototype.transform = function (matrix) {
            var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
            var transformed = BABYLON.Vector3.Zero();
            var index;
            if (this.positions) {
                var position = BABYLON.Vector3.Zero();
                for (index = 0; index < this.positions.length; index += 3) {
                    BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
                    BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
                    this.positions[index] = transformed.x;
                    this.positions[index + 1] = transformed.y;
                    this.positions[index + 2] = transformed.z;
                }
            }
            if (this.normals) {
                var normal = BABYLON.Vector3.Zero();
                for (index = 0; index < this.normals.length; index += 3) {
                    BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
                    BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
                    this.normals[index] = transformed.x;
                    this.normals[index + 1] = transformed.y;
                    this.normals[index + 2] = transformed.z;
                }
            }
            if (this.tangents) {
                var tangent = BABYLON.Vector4.Zero();
                var tangentTransformed = BABYLON.Vector4.Zero();
                for (index = 0; index < this.tangents.length; index += 4) {
                    BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
                    BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
                    this.tangents[index] = tangentTransformed.x;
                    this.tangents[index + 1] = tangentTransformed.y;
                    this.tangents[index + 2] = tangentTransformed.z;
                    this.tangents[index + 3] = tangentTransformed.w;
                }
            }
            if (flip && this.indices) {
                for (index = 0; index < this.indices.length; index += 3) {
                    var tmp = this.indices[index + 1];
                    this.indices[index + 1] = this.indices[index + 2];
                    this.indices[index + 2] = tmp;
                }
            }
            return this;
        };
        /**
         * Merges the passed VertexData into the current one
         * @param other the VertexData to be merged into the current one
         * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
         * @returns the modified VertexData
         */
        VertexData.prototype.merge = function (other, use32BitsIndices) {
            if (use32BitsIndices === void 0) { use32BitsIndices = false; }
            this._validate();
            other._validate();
            if (!this.normals !== !other.normals ||
                !this.tangents !== !other.tangents ||
                !this.uvs !== !other.uvs ||
                !this.uvs2 !== !other.uvs2 ||
                !this.uvs3 !== !other.uvs3 ||
                !this.uvs4 !== !other.uvs4 ||
                !this.uvs5 !== !other.uvs5 ||
                !this.uvs6 !== !other.uvs6 ||
                !this.colors !== !other.colors ||
                !this.matricesIndices !== !other.matricesIndices ||
                !this.matricesWeights !== !other.matricesWeights ||
                !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
                !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
                throw new Error("Cannot merge vertex data that do not have the same set of attributes");
            }
            if (other.indices) {
                if (!this.indices) {
                    this.indices = [];
                }
                var offset = this.positions ? this.positions.length / 3 : 0;
                var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
                if (isSrcTypedArray) {
                    var len = this.indices.length + other.indices.length;
                    var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
                    temp.set(this.indices);
                    var decal = this.indices.length;
                    for (var index = 0; index < other.indices.length; index++) {
                        temp[decal + index] = other.indices[index] + offset;
                    }
                    this.indices = temp;
                }
                else {
                    for (var index = 0; index < other.indices.length; index++) {
                        this.indices.push(other.indices[index] + offset);
                    }
                }
            }
            this.positions = this._mergeElement(this.positions, other.positions);
            this.normals = this._mergeElement(this.normals, other.normals);
            this.tangents = this._mergeElement(this.tangents, other.tangents);
            this.uvs = this._mergeElement(this.uvs, other.uvs);
            this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
            this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
            this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
            this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
            this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
            this.colors = this._mergeElement(this.colors, other.colors);
            this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
            this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
            this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
            this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
            return this;
        };
        VertexData.prototype._mergeElement = function (source, other) {
            if (!source) {
                return other;
            }
            if (!other) {
                return source;
            }
            var len = other.length + source.length;
            var isSrcTypedArray = source instanceof Float32Array;
            var isOthTypedArray = other instanceof Float32Array;
            // use non-loop method when the source is Float32Array
            if (isSrcTypedArray) {
                var ret32 = new Float32Array(len);
                ret32.set(source);
                ret32.set(other, source.length);
                return ret32;
                // source is number[], when other is also use concat
            }
            else if (!isOthTypedArray) {
                return source.concat(other);
                // source is a number[], but other is a Float32Array, loop required
            }
            else {
                var ret = source.slice(0); // copy source to a separate array
                for (var i = 0, len = other.length; i < len; i++) {
                    ret.push(other[i]);
                }
                return ret;
            }
        };
        VertexData.prototype._validate = function () {
            if (!this.positions) {
                throw new Error("Positions are required");
            }
            var getElementCount = function (kind, values) {
                var stride = BABYLON.VertexBuffer.DeduceStride(kind);
                if ((values.length % stride) !== 0) {
                    throw new Error("The " + kind + "s array count must be a multiple of " + stride);
                }
                return values.length / stride;
            };
            var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
            var validateElementCount = function (kind, values) {
                var elementCount = getElementCount(kind, values);
                if (elementCount !== positionsElementCount) {
                    throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
                }
            };
            if (this.normals) {
                validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
            }
            if (this.tangents) {
                validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
            }
            if (this.uvs) {
                validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
            }
            if (this.uvs2) {
                validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
            }
            if (this.uvs3) {
                validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
            }
            if (this.uvs4) {
                validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
            }
            if (this.uvs5) {
                validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
            }
            if (this.uvs6) {
                validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
            }
            if (this.colors) {
                validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
            }
            if (this.matricesIndices) {
                validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
            }
            if (this.matricesWeights) {
                validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
            }
            if (this.matricesIndicesExtra) {
                validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
            }
            if (this.matricesWeightsExtra) {
                validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
            }
        };
        /**
         * Serializes the VertexData
         * @returns a serialized object
         */
        VertexData.prototype.serialize = function () {
            var serializationObject = this.serialize();
            if (this.positions) {
                serializationObject.positions = this.positions;
            }
            if (this.normals) {
                serializationObject.normals = this.normals;
            }
            if (this.tangents) {
                serializationObject.tangents = this.tangents;
            }
            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;
            }
            if (this.matricesIndicesExtra) {
                serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
                serializationObject.matricesIndicesExtra._isExpanded = true;
            }
            if (this.matricesWeightsExtra) {
                serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
            }
            serializationObject.indices = this.indices;
            return serializationObject;
        };
        // Statics
        /**
         * Extracts the vertexData from a mesh
         * @param mesh the mesh from which to extract the VertexData
         * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
         * @param forceCopy indicating that the VertexData must be cloned, optional, default false
         * @returns the object VertexData associated to the passed mesh
         */
        VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
            return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
        };
        /**
         * Extracts the vertexData from the geometry
         * @param geometry the geometry from which to extract the VertexData
         * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
         * @param forceCopy indicating that the VertexData must be cloned, optional, default false
         * @returns the object VertexData associated to the passed mesh
         */
        VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
            return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
        };
        VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
            var result = new VertexData();
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
                result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
                result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
                result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
                result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
                result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
                result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
            }
            if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
                result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
            }
            result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
            return result;
        };
        /**
         * Creates the VertexData for a Ribbon
         * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
          * * pathArray array of paths, each of which an array of successive Vector3
          * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
          * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
          * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
          * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
          * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
          * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
         * @returns the VertexData of the ribbon
         */
        VertexData.CreateRibbon = function (options) {
            var pathArray = options.pathArray;
            var closeArray = options.closeArray || false;
            var closePath = options.closePath || false;
            var invertUV = options.invertUV || false;
            var defaultOffset = Math.floor(pathArray[0].length / 2);
            var offset = options.offset || defaultOffset;
            offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var customUV = options.uvs;
            var customColors = options.colors;
            var positions = [];
            var indices = [];
            var normals = [];
            var uvs = [];
            var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
            var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
            var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
            var vTotalDistance = []; //  vTotalDistance[i] : total distance between points i of first and last path from pathArray
            var minlg; // minimal length among all paths from pathArray
            var lg = []; // array of path lengths : nb of vertex per path
            var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
            var p; // path iterator
            var i; // point iterator
            var j; // point iterator
            // if single path in pathArray
            if (pathArray.length < 2) {
                var ar1 = [];
                var ar2 = [];
                for (i = 0; i < pathArray[0].length - offset; i++) {
                    ar1.push(pathArray[0][i]);
                    ar2.push(pathArray[0][i + offset]);
                }
                pathArray = [ar1, ar2];
            }
            // positions and horizontal distances (u)
            var idc = 0;
            var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
            var path;
            var l;
            minlg = pathArray[0].length;
            var vectlg;
            var dist;
            for (p = 0; p < pathArray.length; p++) {
                uTotalDistance[p] = 0;
                us[p] = [0];
                path = pathArray[p];
                l = path.length;
                minlg = (minlg < l) ? minlg : l;
                j = 0;
                while (j < l) {
                    positions.push(path[j].x, path[j].y, path[j].z);
                    if (j > 0) {
                        vectlg = path[j].subtract(path[j - 1]).length();
                        dist = vectlg + uTotalDistance[p];
                        us[p].push(dist);
                        uTotalDistance[p] = dist;
                    }
                    j++;
                }
                if (closePath) { // an extra hidden vertex is added in the "positions" array
                    j--;
                    positions.push(path[0].x, path[0].y, path[0].z);
                    vectlg = path[j].subtract(path[0]).length();
                    dist = vectlg + uTotalDistance[p];
                    us[p].push(dist);
                    uTotalDistance[p] = dist;
                }
                lg[p] = l + closePathCorr;
                idx[p] = idc;
                idc += (l + closePathCorr);
            }
            // vertical distances (v)
            var path1;
            var path2;
            var vertex1 = null;
            var vertex2 = null;
            for (i = 0; i < minlg + closePathCorr; i++) {
                vTotalDistance[i] = 0;
                vs[i] = [0];
                for (p = 0; p < pathArray.length - 1; p++) {
                    path1 = pathArray[p];
                    path2 = pathArray[p + 1];
                    if (i === minlg) { // closePath
                        vertex1 = path1[0];
                        vertex2 = path2[0];
                    }
                    else {
                        vertex1 = path1[i];
                        vertex2 = path2[i];
                    }
                    vectlg = vertex2.subtract(vertex1).length();
                    dist = vectlg + vTotalDistance[i];
                    vs[i].push(dist);
                    vTotalDistance[i] = dist;
                }
                if (closeArray && vertex2 && vertex1) {
                    path1 = pathArray[p];
                    path2 = pathArray[0];
                    if (i === minlg) { // closePath
                        vertex2 = path2[0];
                    }
                    vectlg = vertex2.subtract(vertex1).length();
                    dist = vectlg + vTotalDistance[i];
                    vTotalDistance[i] = dist;
                }
            }
            // uvs
            var u;
            var v;
            if (customUV) {
                for (p = 0; p < customUV.length; p++) {
                    uvs.push(customUV[p].x, customUV[p].y);
                }
            }
            else {
                for (p = 0; p < pathArray.length; p++) {
                    for (i = 0; i < minlg + closePathCorr; i++) {
                        u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
                        v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
                        if (invertUV) {
                            uvs.push(v, u);
                        }
                        else {
                            uvs.push(u, v);
                        }
                    }
                }
            }
            // indices
            p = 0; // path index
            var pi = 0; // positions array index
            var l1 = lg[p] - 1; // path1 length
            var l2 = lg[p + 1] - 1; // path2 length
            var min = (l1 < l2) ? l1 : l2; // current path stop index
            var shft = idx[1] - idx[0]; // shift
            var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate	on
            while (pi <= min && p < path1nb) { //  stay under min and don't go over next to last path
                // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
                indices.push(pi, pi + shft, pi + 1);
                indices.push(pi + shft + 1, pi + 1, pi + shft);
                pi += 1;
                if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
                    p++;
                    if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
                        shft = idx[0] - idx[p];
                        l1 = lg[p] - 1;
                        l2 = lg[0] - 1;
                    }
                    else {
                        shft = idx[p + 1] - idx[p];
                        l1 = lg[p] - 1;
                        l2 = lg[p + 1] - 1;
                    }
                    pi = idx[p];
                    min = (l1 < l2) ? l1 + pi : l2 + pi;
                }
            }
            // normals
            VertexData.ComputeNormals(positions, indices, normals);
            if (closePath) { // update both the first and last vertex normals to their average value
                var indexFirst = 0;
                var indexLast = 0;
                for (p = 0; p < pathArray.length; p++) {
                    indexFirst = idx[p] * 3;
                    if (p + 1 < pathArray.length) {
                        indexLast = (idx[p + 1] - 1) * 3;
                    }
                    else {
                        indexLast = normals.length - 3;
                    }
                    normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
                    normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
                    normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
                    normals[indexLast] = normals[indexFirst];
                    normals[indexLast + 1] = normals[indexFirst + 1];
                    normals[indexLast + 2] = normals[indexFirst + 2];
                }
            }
            // sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Colors
            var colors = null;
            if (customColors) {
                colors = new Float32Array(customColors.length * 4);
                for (var c = 0; c < customColors.length; c++) {
                    colors[c * 4] = customColors[c].r;
                    colors[c * 4 + 1] = customColors[c].g;
                    colors[c * 4 + 2] = customColors[c].b;
                    colors[c * 4 + 3] = customColors[c].a;
                }
            }
            // Result
            var vertexData = new VertexData();
            var positions32 = new Float32Array(positions);
            var normals32 = new Float32Array(normals);
            var uvs32 = new Float32Array(uvs);
            vertexData.indices = indices;
            vertexData.positions = positions32;
            vertexData.normals = normals32;
            vertexData.uvs = uvs32;
            if (colors) {
                vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
            }
            if (closePath) {
                vertexData._idx = idx;
            }
            return vertexData;
        };
        /**
         * Creates the VertexData for a box
         * @param options an object used to set the following optional parameters for the box, required but can be empty
          * * size sets the width, height and depth of the box to the value of size, optional default 1
          * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
          * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
          * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
          * * faceUV an array of 6 Vector4 elements used to set different images to each box side
          * * faceColors an array of 6 Color3 elements used to set different colors to each box side
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the box
         */
        VertexData.CreateBox = function (options) {
            var normalsSource = [
                new BABYLON.Vector3(0, 0, 1),
                new BABYLON.Vector3(0, 0, -1),
                new BABYLON.Vector3(1, 0, 0),
                new BABYLON.Vector3(-1, 0, 0),
                new BABYLON.Vector3(0, 1, 0),
                new BABYLON.Vector3(0, -1, 0)
            ];
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var width = options.width || options.size || 1;
            var height = options.height || options.size || 1;
            var depth = options.depth || options.size || 1;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var faceUV = options.faceUV || new Array(6);
            var faceColors = options.faceColors;
            var colors = [];
            // default face colors and UV if undefined
            for (var f = 0; f < 6; f++) {
                if (faceUV[f] === undefined) {
                    faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                }
                if (faceColors && faceColors[f] === undefined) {
                    faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                }
            }
            var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
            // Create each face in turn.
            for (var index = 0; index < normalsSource.length; index++) {
                var normal = normalsSource[index];
                // Get two vectors perpendicular to the face normal and to each other.
                var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
                var side2 = BABYLON.Vector3.Cross(normal, side1);
                // Six indices (two triangles) per face.
                var verticesLength = positions.length / 3;
                indices.push(verticesLength);
                indices.push(verticesLength + 1);
                indices.push(verticesLength + 2);
                indices.push(verticesLength);
                indices.push(verticesLength + 2);
                indices.push(verticesLength + 3);
                // Four vertices per face.
                var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].z, faceUV[index].w);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
                vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].x, faceUV[index].w);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
                vertex = normal.add(side1).add(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].x, faceUV[index].y);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
                vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
                positions.push(vertex.x, vertex.y, vertex.z);
                normals.push(normal.x, normal.y, normal.z);
                uvs.push(faceUV[index].z, faceUV[index].y);
                if (faceColors) {
                    colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
                }
            }
            // sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors) {
                var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
                vertexData.colors = totalColors;
            }
            return vertexData;
        };
        /**
         * Creates the VertexData for an ellipsoid, defaults to a sphere
         * @param options an object used to set the following optional parameters for the box, required but can be empty
          * * segments sets the number of horizontal strips optional, default 32
          * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
          * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
          * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
          * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
          * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
          * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the ellipsoid
         */
        VertexData.CreateSphere = function (options) {
            var segments = options.segments || 32;
            var diameterX = options.diameterX || options.diameter || 1;
            var diameterY = options.diameterY || options.diameter || 1;
            var diameterZ = options.diameterZ || options.diameter || 1;
            var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
            var totalZRotationSteps = 2 + segments;
            var totalYRotationSteps = 2 * totalZRotationSteps;
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
                var normalizedZ = zRotationStep / totalZRotationSteps;
                var angleZ = normalizedZ * Math.PI * slice;
                for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
                    var normalizedY = yRotationStep / totalYRotationSteps;
                    var angleY = normalizedY * Math.PI * 2 * arc;
                    var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
                    var rotationY = BABYLON.Matrix.RotationY(angleY);
                    var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
                    var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
                    var vertex = complete.multiply(radius);
                    var normal = complete.divide(radius).normalize();
                    positions.push(vertex.x, vertex.y, vertex.z);
                    normals.push(normal.x, normal.y, normal.z);
                    uvs.push(normalizedY, normalizedZ);
                }
                if (zRotationStep > 0) {
                    var verticesCount = positions.length / 3;
                    for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
                        indices.push((firstIndex));
                        indices.push((firstIndex + 1));
                        indices.push(firstIndex + totalYRotationSteps + 1);
                        indices.push((firstIndex + totalYRotationSteps + 1));
                        indices.push((firstIndex + 1));
                        indices.push((firstIndex + totalYRotationSteps + 2));
                    }
                }
            }
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData for a cylinder, cone or prism
         * @param options an object used to set the following optional parameters for the box, required but can be empty
          * * height sets the height (y direction) of the cylinder, optional, default 2
          * * diameterTop sets the diameter of the top of the cone, overwrites diameter,  optional, default diameter
          * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter,  optional, default diameter
          * * diameter sets the diameter of the top and bottom of the cone, optional default 1
          * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
          * * subdivisions` the number of rings along the cylinder height, optional, default 1
          * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
          * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
          * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
          * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
          * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the cylinder, cone or prism
         */
        VertexData.CreateCylinder = function (options) {
            var height = options.height || 2;
            var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
            var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
            var tessellation = options.tessellation || 24;
            var subdivisions = options.subdivisions || 1;
            var hasRings = options.hasRings ? true : false;
            var enclose = options.enclose ? true : false;
            var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var faceUV = options.faceUV || new Array(3);
            var faceColors = options.faceColors;
            // default face colors and UV if undefined
            var quadNb = (arc !== 1 && enclose) ? 2 : 0;
            var ringNb = (hasRings) ? subdivisions : 1;
            var surfaceNb = 2 + (1 + quadNb) * ringNb;
            var f;
            for (f = 0; f < surfaceNb; f++) {
                if (faceColors && faceColors[f] === undefined) {
                    faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                }
            }
            for (f = 0; f < surfaceNb; f++) {
                if (faceUV && faceUV[f] === undefined) {
                    faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                }
            }
            var indices = new Array();
            var positions = new Array();
            var normals = new Array();
            var uvs = new Array();
            var colors = new Array();
            var angle_step = Math.PI * 2 * arc / tessellation;
            var angle;
            var h;
            var radius;
            var tan = (diameterBottom - diameterTop) / 2 / height;
            var ringVertex = BABYLON.Vector3.Zero();
            var ringNormal = BABYLON.Vector3.Zero();
            var ringFirstVertex = BABYLON.Vector3.Zero();
            var ringFirstNormal = BABYLON.Vector3.Zero();
            var quadNormal = BABYLON.Vector3.Zero();
            var Y = BABYLON.Axis.Y;
            // positions, normals, uvs
            var i;
            var j;
            var r;
            var ringIdx = 1;
            var s = 1; // surface index
            var cs = 0;
            var v = 0;
            for (i = 0; i <= subdivisions; i++) {
                h = i / subdivisions;
                radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
                ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
                for (r = 0; r < ringIdx; r++) {
                    if (hasRings) {
                        s += r;
                    }
                    if (enclose) {
                        s += 2 * r;
                    }
                    for (j = 0; j <= tessellation; j++) {
                        angle = j * angle_step;
                        // position
                        ringVertex.x = Math.cos(-angle) * radius;
                        ringVertex.y = -height / 2 + h * height;
                        ringVertex.z = Math.sin(-angle) * radius;
                        // normal
                        if (diameterTop === 0 && i === subdivisions) {
                            // if no top cap, reuse former normals
                            ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
                            ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
                            ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
                        }
                        else {
                            ringNormal.x = ringVertex.x;
                            ringNormal.z = ringVertex.z;
                            ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
                            ringNormal.normalize();
                        }
                        // keep first ring vertex values for enclose
                        if (j === 0) {
                            ringFirstVertex.copyFrom(ringVertex);
                            ringFirstNormal.copyFrom(ringNormal);
                        }
                        positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
                        normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
                        if (hasRings) {
                            v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
                        }
                        else {
                            v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
                        }
                        uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
                        if (faceColors) {
                            colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
                        }
                    }
                    // if enclose, add four vertices and their dedicated normals
                    if (arc !== 1 && enclose) {
                        positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
                        positions.push(0, ringVertex.y, 0);
                        positions.push(0, ringVertex.y, 0);
                        positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
                        BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
                        quadNormal.normalize();
                        normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
                        BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
                        quadNormal.normalize();
                        normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
                        if (hasRings) {
                            v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
                        }
                        else {
                            v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
                        }
                        uvs.push(faceUV[s + 1].x, v);
                        uvs.push(faceUV[s + 1].z, v);
                        if (hasRings) {
                            v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
                        }
                        else {
                            v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
                        }
                        uvs.push(faceUV[s + 2].x, v);
                        uvs.push(faceUV[s + 2].z, v);
                        if (faceColors) {
                            colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
                            colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
                            colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
                            colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
                        }
                    }
                    if (cs !== s) {
                        cs = s;
                    }
                }
            }
            // indices
            var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
            var s;
            i = 0;
            for (s = 0; s < subdivisions; s++) {
                var i0 = 0;
                var i1 = 0;
                var i2 = 0;
                var i3 = 0;
                for (j = 0; j < tessellation; j++) {
                    i0 = i * (e + 1) + j;
                    i1 = (i + 1) * (e + 1) + j;
                    i2 = i * (e + 1) + (j + 1);
                    i3 = (i + 1) * (e + 1) + (j + 1);
                    indices.push(i0, i1, i2);
                    indices.push(i3, i2, i1);
                }
                if (arc !== 1 && enclose) { // if enclose, add two quads
                    indices.push(i0 + 2, i1 + 2, i2 + 2);
                    indices.push(i3 + 2, i2 + 2, i1 + 2);
                    indices.push(i0 + 4, i1 + 4, i2 + 4);
                    indices.push(i3 + 4, i2 + 4, i1 + 4);
                }
                i = (hasRings) ? (i + 2) : (i + 1);
            }
            // Caps
            var createCylinderCap = function (isTop) {
                var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
                if (radius === 0) {
                    return;
                }
                // Cap positions, normals & uvs
                var angle;
                var circleVector;
                var i;
                var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
                var c = null;
                if (faceColors) {
                    c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
                }
                // cap center
                var vbase = positions.length / 3;
                var offset = isTop ? height / 2 : -height / 2;
                var center = new BABYLON.Vector3(0, offset, 0);
                positions.push(center.x, center.y, center.z);
                normals.push(0, isTop ? 1 : -1, 0);
                uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
                if (c) {
                    colors.push(c.r, c.g, c.b, c.a);
                }
                var textureScale = new BABYLON.Vector2(0.5, 0.5);
                for (i = 0; i <= tessellation; i++) {
                    angle = Math.PI * 2 * i * arc / tessellation;
                    var cos = Math.cos(-angle);
                    var sin = Math.sin(-angle);
                    circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
                    var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
                    positions.push(circleVector.x, circleVector.y, circleVector.z);
                    normals.push(0, isTop ? 1 : -1, 0);
                    uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
                    if (c) {
                        colors.push(c.r, c.g, c.b, c.a);
                    }
                }
                // Cap indices
                for (i = 0; i < tessellation; i++) {
                    if (!isTop) {
                        indices.push(vbase);
                        indices.push(vbase + (i + 1));
                        indices.push(vbase + (i + 2));
                    }
                    else {
                        indices.push(vbase);
                        indices.push(vbase + (i + 2));
                        indices.push(vbase + (i + 1));
                    }
                }
            };
            // add caps to geometry
            createCylinderCap(false);
            createCylinderCap(true);
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors) {
                vertexData.colors = colors;
            }
            return vertexData;
        };
        /**
         * Creates the VertexData for a torus
         * @param options an object used to set the following optional parameters for the box, required but can be empty
          * * diameter the diameter of the torus, optional default 1
          * * thickness the diameter of the tube forming the torus, optional default 0.5
          * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the torus
         */
        VertexData.CreateTorus = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var diameter = options.diameter || 1;
            var thickness = options.thickness || 0.5;
            var tessellation = options.tessellation || 16;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var stride = tessellation + 1;
            for (var i = 0; i <= tessellation; i++) {
                var u = i / tessellation;
                var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
                var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
                for (var j = 0; j <= tessellation; j++) {
                    var v = 1 - j / tessellation;
                    var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
                    var dx = Math.cos(innerAngle);
                    var dy = Math.sin(innerAngle);
                    // Create a vertex.
                    var normal = new BABYLON.Vector3(dx, dy, 0);
                    var position = normal.scale(thickness / 2);
                    var textureCoordinate = new BABYLON.Vector2(u, v);
                    position = BABYLON.Vector3.TransformCoordinates(position, transform);
                    normal = BABYLON.Vector3.TransformNormal(normal, transform);
                    positions.push(position.x, position.y, position.z);
                    normals.push(normal.x, normal.y, normal.z);
                    uvs.push(textureCoordinate.x, textureCoordinate.y);
                    // And create indices for two triangles.
                    var nextI = (i + 1) % stride;
                    var nextJ = (j + 1) % stride;
                    indices.push(i * stride + j);
                    indices.push(i * stride + nextJ);
                    indices.push(nextI * stride + j);
                    indices.push(i * stride + nextJ);
                    indices.push(nextI * stride + nextJ);
                    indices.push(nextI * stride + j);
                }
            }
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData of the LineSystem
         * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
         *  - lines an array of lines, each line being an array of successive Vector3
         *  - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
         * @returns the VertexData of the LineSystem
         */
        VertexData.CreateLineSystem = function (options) {
            var indices = [];
            var positions = [];
            var lines = options.lines;
            var colors = options.colors;
            var vertexColors = [];
            var idx = 0;
            for (var l = 0; l < lines.length; l++) {
                var points = lines[l];
                for (var index = 0; index < points.length; index++) {
                    positions.push(points[index].x, points[index].y, points[index].z);
                    if (colors) {
                        var color = colors[l];
                        vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
                    }
                    if (index > 0) {
                        indices.push(idx - 1);
                        indices.push(idx);
                    }
                    idx++;
                }
            }
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            if (colors) {
                vertexData.colors = vertexColors;
            }
            return vertexData;
        };
        /**
         * Create the VertexData for a DashedLines
         * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
         *  - points an array successive Vector3
         *  - dashSize the size of the dashes relative to the dash number, optional, default 3
         *  - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
         *  - dashNb the intended total number of dashes, optional, default 200
         * @returns the VertexData for the DashedLines
         */
        VertexData.CreateDashedLines = function (options) {
            var dashSize = options.dashSize || 3;
            var gapSize = options.gapSize || 1;
            var dashNb = options.dashNb || 200;
            var points = options.points;
            var positions = new Array();
            var indices = new Array();
            var curvect = BABYLON.Vector3.Zero();
            var lg = 0;
            var nb = 0;
            var shft = 0;
            var dashshft = 0;
            var curshft = 0;
            var idx = 0;
            var i = 0;
            for (i = 0; i < points.length - 1; i++) {
                points[i + 1].subtractToRef(points[i], curvect);
                lg += curvect.length();
            }
            shft = lg / dashNb;
            dashshft = dashSize * shft / (dashSize + gapSize);
            for (i = 0; i < points.length - 1; i++) {
                points[i + 1].subtractToRef(points[i], curvect);
                nb = Math.floor(curvect.length() / shft);
                curvect.normalize();
                for (var j = 0; j < nb; j++) {
                    curshft = shft * j;
                    positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
                    positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
                    indices.push(idx, idx + 1);
                    idx += 2;
                }
            }
            // Result
            var vertexData = new VertexData();
            vertexData.positions = positions;
            vertexData.indices = indices;
            return vertexData;
        };
        /**
         * Creates the VertexData for a Ground
         * @param options an object used to set the following optional parameters for the Ground, required but can be empty
         *  - width the width (x direction) of the ground, optional, default 1
         *  - height the height (z direction) of the ground, optional, default 1
         *  - subdivisions the number of subdivisions per side, optional, default 1
         * @returns the VertexData of the Ground
         */
        VertexData.CreateGround = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var row, col;
            var width = options.width || 1;
            var height = options.height || 1;
            var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
            var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
            for (row = 0; row <= subdivisionsY; row++) {
                for (col = 0; col <= subdivisionsX; col++) {
                    var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
                    var normal = new BABYLON.Vector3(0, 1.0, 0);
                    positions.push(position.x, position.y, position.z);
                    normals.push(normal.x, normal.y, normal.z);
                    uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
                }
            }
            for (row = 0; row < subdivisionsY; row++) {
                for (col = 0; col < subdivisionsX; col++) {
                    indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
                    indices.push(col + 1 + row * (subdivisionsX + 1));
                    indices.push(col + row * (subdivisionsX + 1));
                    indices.push(col + (row + 1) * (subdivisionsX + 1));
                    indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
                    indices.push(col + row * (subdivisionsX + 1));
                }
            }
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData for a TiledGround by subdividing the ground into tiles
         * @param options an object used to set the following optional parameters for the Ground, required but can be empty
          * * xmin the ground minimum X coordinate, optional, default -1
          * * zmin the ground minimum Z coordinate, optional, default -1
          * * xmax the ground maximum X coordinate, optional, default 1
          * * zmax the ground maximum Z coordinate, optional, default 1
          * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
          * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
         * @returns the VertexData of the TiledGround
         */
        VertexData.CreateTiledGround = function (options) {
            var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
            var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
            var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
            var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
            var subdivisions = options.subdivisions || { w: 1, h: 1 };
            var precision = options.precision || { w: 1, h: 1 };
            var indices = new Array();
            var positions = new Array();
            var normals = new Array();
            var uvs = new Array();
            var row, col, tileRow, tileCol;
            subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
            subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
            precision.w = (precision.w < 1) ? 1 : precision.w;
            precision.h = (precision.h < 1) ? 1 : precision.h;
            var tileSize = {
                'w': (xmax - xmin) / subdivisions.w,
                'h': (zmax - zmin) / subdivisions.h
            };
            function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
                // Indices
                var base = positions.length / 3;
                var rowLength = precision.w + 1;
                for (row = 0; row < precision.h; row++) {
                    for (col = 0; col < precision.w; col++) {
                        var square = [
                            base + col + row * rowLength,
                            base + (col + 1) + row * rowLength,
                            base + (col + 1) + (row + 1) * rowLength,
                            base + col + (row + 1) * rowLength
                        ];
                        indices.push(square[1]);
                        indices.push(square[2]);
                        indices.push(square[3]);
                        indices.push(square[0]);
                        indices.push(square[1]);
                        indices.push(square[3]);
                    }
                }
                // Position, normals and uvs
                var position = BABYLON.Vector3.Zero();
                var normal = new BABYLON.Vector3(0, 1.0, 0);
                for (row = 0; row <= precision.h; row++) {
                    position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
                    for (col = 0; col <= precision.w; col++) {
                        position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
                        position.y = 0;
                        positions.push(position.x, position.y, position.z);
                        normals.push(normal.x, normal.y, normal.z);
                        uvs.push(col / precision.w, row / precision.h);
                    }
                }
            }
            for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
                for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
                    applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
                }
            }
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData of the Ground designed from a heightmap
         * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
          * * width the width (x direction) of the ground
          * * height the height (z direction) of the ground
          * * subdivisions the number of subdivisions per side
          * * minHeight the minimum altitude on the ground, optional, default 0
          * * maxHeight the maximum altitude on the ground, optional default 1
          * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
          * * buffer the array holding the image color data
          * * bufferWidth the width of image
          * * bufferHeight the height of image
          * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
         * @returns the VertexData of the Ground designed from a heightmap
         */
        VertexData.CreateGroundFromHeightMap = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var row, col;
            var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
            var alphaFilter = options.alphaFilter || 0.0;
            // Vertices
            for (row = 0; row <= options.subdivisions; row++) {
                for (col = 0; col <= options.subdivisions; col++) {
                    var position = new BABYLON.Vector3((col * options.width) / options.subdivisions - (options.width / 2.0), 0, ((options.subdivisions - row) * options.height) / options.subdivisions - (options.height / 2.0));
                    // Compute height
                    var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
                    var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
                    var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
                    var r = options.buffer[pos] / 255.0;
                    var g = options.buffer[pos + 1] / 255.0;
                    var b = options.buffer[pos + 2] / 255.0;
                    var a = options.buffer[pos + 3] / 255.0;
                    var gradient = r * filter.r + g * filter.g + b * filter.b;
                    // If our alpha channel is not within our filter then we will assign a 'special' height
                    // Then when building the indices, we will ignore any vertex that is using the special height
                    if (a >= alphaFilter) {
                        position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
                    }
                    else {
                        position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
                    }
                    // Add  vertex
                    positions.push(position.x, position.y, position.z);
                    normals.push(0, 0, 0);
                    uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
                }
            }
            // Indices
            for (row = 0; row < options.subdivisions; row++) {
                for (col = 0; col < options.subdivisions; col++) {
                    // Calculate Indices
                    var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
                    var idx2 = (col + 1 + row * (options.subdivisions + 1));
                    var idx3 = (col + row * (options.subdivisions + 1));
                    var idx4 = (col + (row + 1) * (options.subdivisions + 1));
                    // Check that all indices are visible (based on our special height)
                    // Only display the vertex if all Indices are visible
                    // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
                    var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
                    var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
                    var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
                    if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
                        indices.push(idx1);
                        indices.push(idx2);
                        indices.push(idx3);
                    }
                    var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
                    if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
                        indices.push(idx4);
                        indices.push(idx1);
                        indices.push(idx3);
                    }
                }
            }
            // Normals
            VertexData.ComputeNormals(positions, indices, normals);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData for a Plane
         * @param options an object used to set the following optional parameters for the plane, required but can be empty
          * * size sets the width and height of the plane to the value of size, optional default 1
          * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
          * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the box
         */
        VertexData.CreatePlane = function (options) {
            var indices = [];
            var positions = [];
            var normals = [];
            var uvs = [];
            var width = options.width || options.size || 1;
            var height = options.height || options.size || 1;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            // Vertices
            var halfWidth = width / 2.0;
            var halfHeight = height / 2.0;
            positions.push(-halfWidth, -halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(0.0, 0.0);
            positions.push(halfWidth, -halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(1.0, 0.0);
            positions.push(halfWidth, halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(1.0, 1.0);
            positions.push(-halfWidth, halfHeight, 0);
            normals.push(0, 0, -1.0);
            uvs.push(0.0, 1.0);
            // Indices
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData of the Disc or regular Polygon
         * @param options an object used to set the following optional parameters for the disc, required but can be empty
          * * radius the radius of the disc, optional default 0.5
          * * tessellation the number of polygon sides, optional, default 64
          * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the box
         */
        VertexData.CreateDisc = function (options) {
            var positions = new Array();
            var indices = new Array();
            var normals = new Array();
            var uvs = new Array();
            var radius = options.radius || 0.5;
            var tessellation = options.tessellation || 64;
            var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            // positions and uvs
            positions.push(0, 0, 0); // disc center first
            uvs.push(0.5, 0.5);
            var theta = Math.PI * 2 * arc;
            var step = theta / tessellation;
            for (var a = 0; a < theta; a += step) {
                var x = Math.cos(a);
                var y = Math.sin(a);
                var u = (x + 1) / 2;
                var v = (1 - y) / 2;
                positions.push(radius * x, radius * y, 0);
                uvs.push(u, v);
            }
            if (arc === 1) {
                positions.push(positions[3], positions[4], positions[5]); // close the circle
                uvs.push(uvs[2], uvs[3]);
            }
            //indices
            var vertexNb = positions.length / 3;
            for (var i = 1; i < vertexNb - 1; i++) {
                indices.push(i + 1, 0, i);
            }
            // result
            VertexData.ComputeNormals(positions, indices, normals);
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        /**
         * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
         * All parameters are provided by MeshBuilder.CreatePolygon as needed
         * @param polygon a mesh built from polygonTriangulation.build()
         * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
         * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
         * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
         * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the Polygon
         */
        VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
            var faceUV = fUV || new Array(3);
            var faceColors = fColors;
            var colors = [];
            // default face colors and UV if undefined
            for (var f = 0; f < 3; f++) {
                if (faceUV[f] === undefined) {
                    faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                }
                if (faceColors && faceColors[f] === undefined) {
                    faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                }
            }
            var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var indices = polygon.getIndices();
            // set face colours and textures
            var idx = 0;
            var face = 0;
            for (var index = 0; index < normals.length; index += 3) {
                //Edge Face  no. 1
                if (Math.abs(normals[index + 1]) < 0.001) {
                    face = 1;
                }
                //Top Face  no. 0
                if (Math.abs(normals[index + 1] - 1) < 0.001) {
                    face = 0;
                }
                //Bottom Face  no. 2
                if (Math.abs(normals[index + 1] + 1) < 0.001) {
                    face = 2;
                }
                idx = index / 3;
                uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
                uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
                if (faceColors) {
                    colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
                }
            }
            // sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors) {
                var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
                vertexData.colors = totalColors;
            }
            return vertexData;
        };
        /**
         * Creates the VertexData of the IcoSphere
         * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
          * * radius the radius of the IcoSphere, optional default 1
          * * radiusX allows stretching in the x direction, optional, default radius
          * * radiusY allows stretching in the y direction, optional, default radius
          * * radiusZ allows stretching in the z direction, optional, default radius
          * * flat when true creates a flat shaded mesh, optional, default true
          * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the IcoSphere
         */
        VertexData.CreateIcoSphere = function (options) {
            var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var radius = options.radius || 1;
            var flat = (options.flat === undefined) ? true : options.flat;
            var subdivisions = options.subdivisions || 4;
            var radiusX = options.radiusX || radius;
            var radiusY = options.radiusY || radius;
            var radiusZ = options.radiusZ || radius;
            var t = (1 + Math.sqrt(5)) / 2;
            // 12 vertex x,y,z
            var ico_vertices = [
                -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
                0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
                t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
            ];
            // index of 3 vertex makes a face of icopshere
            var ico_indices = [
                0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
                1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
                14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
                4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
            ];
            // vertex for uv have aliased position, not for UV
            var vertices_unalias_id = [
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                // vertex alias
                0,
                2,
                3,
                3,
                3,
                4,
                7,
                8,
                9,
                9,
                10,
                11 // 23: B + 12
            ];
            // uv as integer step (not pixels !)
            var ico_vertexuv = [
                5, 1, 3, 1, 6, 4, 0, 0,
                5, 3, 4, 2, 2, 2, 4, 0,
                2, 0, 1, 1, 6, 0, 6, 2,
                // vertex alias (for same vertex on different faces)
                0, 4,
                3, 3,
                4, 4,
                3, 1,
                4, 2,
                4, 4,
                0, 2,
                1, 1,
                2, 2,
                3, 3,
                1, 3,
                2, 4 // 23: B + 12
            ];
            // Vertices[0, 1, ...9, A, B] : position on UV plane
            // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
            // First island of uv mapping
            // v = 4h          3+  2
            // v = 3h        9+  4
            // v = 2h      9+  5   B
            // v = 1h    9   1   0
            // v = 0h  3   8   7   A
            //     u = 0 1 2 3 4 5 6  *a
            // Second island of uv mapping
            // v = 4h  0+  B+  4+
            // v = 3h    A+  2+
            // v = 2h  7+  6   3+
            // v = 1h    8+  3+
            // v = 0h
            //     u = 0 1 2 3 4 5 6  *a
            // Face layout on texture UV mapping
            // ============
            // \ 4  /\ 16 /   ======
            //  \  /  \  /   /\ 11 /
            //   \/ 7  \/   /  \  /
            //    =======  / 10 \/
            //   /\ 17 /\  =======
            //  /  \  /  \ \ 15 /\
            // / 8  \/ 12 \ \  /  \
            // ============  \/ 6  \
            // \ 18 /\  ============
            //  \  /  \ \ 5  /\ 0  /
            //   \/ 13 \ \  /  \  /
            //   =======  \/ 1  \/
            //       =============
            //      /\ 19 /\  2 /\
            //     /  \  /  \  /  \
            //    / 14 \/ 9  \/  3 \
            //   ===================
            // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
            var ustep = 138 / 1024;
            var vstep = 239 / 1024;
            var uoffset = 60 / 1024;
            var voffset = 26 / 1024;
            // Second island should have margin, not to touch the first island
            // avoid any borderline artefact in pixel rounding
            var island_u_offset = -40 / 1024;
            var island_v_offset = +20 / 1024;
            // face is either island 0 or 1 :
            // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
            var island = [
                0, 0, 0, 0, 1,
                0, 0, 1, 1, 0,
                0, 0, 1, 1, 0,
                0, 1, 1, 1, 0 //  15 - 19
            ];
            var indices = new Array();
            var positions = new Array();
            var normals = new Array();
            var uvs = new Array();
            var current_indice = 0;
            // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
            var face_vertex_pos = new Array(3);
            var face_vertex_uv = new Array(3);
            var v012;
            for (v012 = 0; v012 < 3; v012++) {
                face_vertex_pos[v012] = BABYLON.Vector3.Zero();
                face_vertex_uv[v012] = BABYLON.Vector2.Zero();
            }
            // create all with normals
            for (var face = 0; face < 20; face++) {
                // 3 vertex per face
                for (v012 = 0; v012 < 3; v012++) {
                    // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
                    var v_id = ico_indices[3 * face + v012];
                    // vertex have 3D position (x,y,z)
                    face_vertex_pos[v012].copyFromFloats(ico_vertices[3 * vertices_unalias_id[v_id]], ico_vertices[3 * vertices_unalias_id[v_id] + 1], ico_vertices[3 * vertices_unalias_id[v_id] + 2]);
                    // Normalize to get normal, then scale to radius
                    face_vertex_pos[v012].normalize().scaleInPlace(radius);
                    // uv Coordinates from vertex ID
                    face_vertex_uv[v012].copyFromFloats(ico_vertexuv[2 * v_id] * ustep + uoffset + island[face] * island_u_offset, ico_vertexuv[2 * v_id + 1] * vstep + voffset + island[face] * island_v_offset);
                }
                // Subdivide the face (interpolate pos, norm, uv)
                // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
                // - norm is linear interpolation of vertex corner normal
                //   (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
                // - uv is linear interpolation
                //
                // Topology is as below for sub-divide by 2
                // vertex shown as v0,v1,v2
                // interp index is i1 to progress in range [v0,v1[
                // interp index is i2 to progress in range [v0,v2[
                // face index as  (i1,i2)  for /\  : (i1,i2),(i1+1,i2),(i1,i2+1)
                //            and (i1,i2)' for \/  : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
                //
                //
                //                    i2    v2
                //                    ^    ^
                //                   /    / \
                //                  /    /   \
                //                 /    /     \
                //                /    / (0,1) \
                //               /    #---------\
                //              /    / \ (0,0)'/ \
                //             /    /   \     /   \
                //            /    /     \   /     \
                //           /    / (0,0) \ / (1,0) \
                //          /    #---------#---------\
                //              v0                    v1
                //
                //              --------------------> i1
                //
                // interp of (i1,i2):
                //  along i2 :  x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
                //  along i1 :  lerp(x0,x1, i1/(S-i2))
                //
                // centroid of triangle is needed to get help normal computation
                //  (c1,c2) are used for centroid location
                var interp_vertex = function (i1, i2, c1, c2) {
                    // vertex is interpolated from
                    //   - face_vertex_pos[0..2]
                    //   - face_vertex_uv[0..2]
                    var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
                    var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
                    var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
                    pos_interp.normalize();
                    var vertex_normal;
                    if (flat) {
                        // in flat mode, recalculate normal as face centroid normal
                        var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
                        var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
                        vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
                    }
                    else {
                        // in smooth mode, recalculate normal from each single vertex position
                        vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
                    }
                    // Vertex normal need correction due to X,Y,Z radius scaling
                    vertex_normal.x /= radiusX;
                    vertex_normal.y /= radiusY;
                    vertex_normal.z /= radiusZ;
                    vertex_normal.normalize();
                    var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
                    var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
                    var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
                    positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
                    normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
                    uvs.push(uv_interp.x, uv_interp.y);
                    // push each vertex has member of a face
                    // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
                    indices.push(current_indice);
                    current_indice++;
                };
                for (var i2 = 0; i2 < subdivisions; i2++) {
                    for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
                        // face : (i1,i2)  for /\  :
                        // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
                        interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
                        interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
                        interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
                        if (i1 + i2 + 1 < subdivisions) {
                            // face : (i1,i2)' for \/  :
                            // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
                            interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
                            interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
                            interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
                        }
                    }
                }
            }
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
        /**
         * Creates the VertexData for a Polyhedron
         * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
         * * type provided types are:
         *  * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
         *  * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
         * * size the size of the IcoSphere, optional default 1
         * * sizeX allows stretching in the x direction, optional, default size
         * * sizeY allows stretching in the y direction, optional, default size
         * * sizeZ allows stretching in the z direction, optional, default size
         * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
         * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
         * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
         * * flat when true creates a flat shaded mesh, optional, default true
         * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
         * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
         * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the Polyhedron
         */
        VertexData.CreatePolyhedron = function (options) {
            // provided polyhedron types :
            // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
            // 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20)
            var polyhedra = [];
            polyhedra[0] = { vertex: [[0, 0, 1.732051], [1.632993, 0, -0.5773503], [-0.8164966, 1.414214, -0.5773503], [-0.8164966, -1.414214, -0.5773503]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]] };
            polyhedra[1] = { vertex: [[0, 0, 1.414214], [1.414214, 0, 0], [0, 1.414214, 0], [-1.414214, 0, 0], [0, -1.414214, 0], [0, 0, -1.414214]], face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [1, 4, 5], [1, 5, 2], [2, 5, 3], [3, 5, 4]] };
            polyhedra[2] = {
                vertex: [[0, 0, 1.070466], [0.7136442, 0, 0.7978784], [-0.3568221, 0.618034, 0.7978784], [-0.3568221, -0.618034, 0.7978784], [0.7978784, 0.618034, 0.3568221], [0.7978784, -0.618034, 0.3568221], [-0.9341724, 0.381966, 0.3568221], [0.1362939, 1, 0.3568221], [0.1362939, -1, 0.3568221], [-0.9341724, -0.381966, 0.3568221], [0.9341724, 0.381966, -0.3568221], [0.9341724, -0.381966, -0.3568221], [-0.7978784, 0.618034, -0.3568221], [-0.1362939, 1, -0.3568221], [-0.1362939, -1, -0.3568221], [-0.7978784, -0.618034, -0.3568221], [0.3568221, 0.618034, -0.7978784], [0.3568221, -0.618034, -0.7978784], [-0.7136442, 0, -0.7978784], [0, 0, -1.070466]],
                face: [[0, 1, 4, 7, 2], [0, 2, 6, 9, 3], [0, 3, 8, 5, 1], [1, 5, 11, 10, 4], [2, 7, 13, 12, 6], [3, 9, 15, 14, 8], [4, 10, 16, 13, 7], [5, 8, 14, 17, 11], [6, 12, 18, 15, 9], [10, 11, 17, 19, 16], [12, 13, 16, 19, 18], [14, 15, 18, 19, 17]]
            };
            polyhedra[3] = {
                vertex: [[0, 0, 1.175571], [1.051462, 0, 0.5257311], [0.3249197, 1, 0.5257311], [-0.8506508, 0.618034, 0.5257311], [-0.8506508, -0.618034, 0.5257311], [0.3249197, -1, 0.5257311], [0.8506508, 0.618034, -0.5257311], [0.8506508, -0.618034, -0.5257311], [-0.3249197, 1, -0.5257311], [-1.051462, 0, -0.5257311], [-0.3249197, -1, -0.5257311], [0, 0, -1.175571]],
                face: [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 5], [0, 5, 1], [1, 5, 7], [1, 7, 6], [1, 6, 2], [2, 6, 8], [2, 8, 3], [3, 8, 9], [3, 9, 4], [4, 9, 10], [4, 10, 5], [5, 10, 7], [6, 7, 11], [6, 11, 8], [7, 10, 11], [8, 11, 9], [9, 11, 10]]
            };
            polyhedra[4] = {
                vertex: [[0, 0, 1.070722], [0.7148135, 0, 0.7971752], [-0.104682, 0.7071068, 0.7971752], [-0.6841528, 0.2071068, 0.7971752], [-0.104682, -0.7071068, 0.7971752], [0.6101315, 0.7071068, 0.5236279], [1.04156, 0.2071068, 0.1367736], [0.6101315, -0.7071068, 0.5236279], [-0.3574067, 1, 0.1367736], [-0.7888348, -0.5, 0.5236279], [-0.9368776, 0.5, 0.1367736], [-0.3574067, -1, 0.1367736], [0.3574067, 1, -0.1367736], [0.9368776, -0.5, -0.1367736], [0.7888348, 0.5, -0.5236279], [0.3574067, -1, -0.1367736], [-0.6101315, 0.7071068, -0.5236279], [-1.04156, -0.2071068, -0.1367736], [-0.6101315, -0.7071068, -0.5236279], [0.104682, 0.7071068, -0.7971752], [0.6841528, -0.2071068, -0.7971752], [0.104682, -0.7071068, -0.7971752], [-0.7148135, 0, -0.7971752], [0, 0, -1.070722]],
                face: [[0, 2, 3], [1, 6, 5], [4, 9, 11], [7, 15, 13], [8, 16, 10], [12, 14, 19], [17, 22, 18], [20, 21, 23], [0, 1, 5, 2], [0, 3, 9, 4], [0, 4, 7, 1], [1, 7, 13, 6], [2, 5, 12, 8], [2, 8, 10, 3], [3, 10, 17, 9], [4, 11, 15, 7], [5, 6, 14, 12], [6, 13, 20, 14], [8, 12, 19, 16], [9, 17, 18, 11], [10, 16, 22, 17], [11, 18, 21, 15], [13, 15, 21, 20], [14, 20, 23, 19], [16, 19, 23, 22], [18, 22, 23, 21]]
            };
            polyhedra[5] = { vertex: [[0, 0, 1.322876], [1.309307, 0, 0.1889822], [-0.9819805, 0.8660254, 0.1889822], [0.1636634, -1.299038, 0.1889822], [0.3273268, 0.8660254, -0.9449112], [-0.8183171, -0.4330127, -0.9449112]], face: [[0, 3, 1], [2, 4, 5], [0, 1, 4, 2], [0, 2, 5, 3], [1, 3, 5, 4]] };
            polyhedra[6] = { vertex: [[0, 0, 1.159953], [1.013464, 0, 0.5642542], [-0.3501431, 0.9510565, 0.5642542], [-0.7715208, -0.6571639, 0.5642542], [0.6633206, 0.9510565, -0.03144481], [0.8682979, -0.6571639, -0.3996071], [-1.121664, 0.2938926, -0.03144481], [-0.2348831, -1.063314, -0.3996071], [0.5181548, 0.2938926, -0.9953061], [-0.5850262, -0.112257, -0.9953061]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 9, 7], [5, 7, 9, 8], [0, 3, 7, 5, 1], [2, 4, 8, 9, 6]] };
            polyhedra[7] = { vertex: [[0, 0, 1.118034], [0.8944272, 0, 0.6708204], [-0.2236068, 0.8660254, 0.6708204], [-0.7826238, -0.4330127, 0.6708204], [0.6708204, 0.8660254, 0.2236068], [1.006231, -0.4330127, -0.2236068], [-1.006231, 0.4330127, 0.2236068], [-0.6708204, -0.8660254, -0.2236068], [0.7826238, 0.4330127, -0.6708204], [0.2236068, -0.8660254, -0.6708204], [-0.8944272, 0, -0.6708204], [0, 0, -1.118034]], face: [[0, 1, 4, 2], [0, 2, 6, 3], [1, 5, 8, 4], [3, 6, 10, 7], [5, 9, 11, 8], [7, 10, 11, 9], [0, 3, 7, 9, 5, 1], [2, 4, 8, 11, 10, 6]] };
            polyhedra[8] = { vertex: [[-0.729665, 0.670121, 0.319155], [-0.655235, -0.29213, -0.754096], [-0.093922, -0.607123, 0.537818], [0.702196, 0.595691, 0.485187], [0.776626, -0.36656, -0.588064]], face: [[1, 4, 2], [0, 1, 2], [3, 0, 2], [4, 3, 2], [4, 1, 0, 3]] };
            polyhedra[9] = { vertex: [[-0.868849, -0.100041, 0.61257], [-0.329458, 0.976099, 0.28078], [-0.26629, -0.013796, -0.477654], [-0.13392, -1.034115, 0.229829], [0.738834, 0.707117, -0.307018], [0.859683, -0.535264, -0.338508]], face: [[3, 0, 2], [5, 3, 2], [4, 5, 2], [1, 4, 2], [0, 1, 2], [0, 3, 5, 4, 1]] };
            polyhedra[10] = { vertex: [[-0.610389, 0.243975, 0.531213], [-0.187812, -0.48795, -0.664016], [-0.187812, 0.9759, -0.664016], [0.187812, -0.9759, 0.664016], [0.798201, 0.243975, 0.132803]], face: [[1, 3, 0], [3, 4, 0], [3, 1, 4], [0, 2, 1], [0, 4, 2], [2, 4, 1]] };
            polyhedra[11] = { vertex: [[-1.028778, 0.392027, -0.048786], [-0.640503, -0.646161, 0.621837], [-0.125162, -0.395663, -0.540059], [0.004683, 0.888447, -0.651988], [0.125161, 0.395663, 0.540059], [0.632925, -0.791376, 0.433102], [1.031672, 0.157063, -0.354165]], face: [[3, 2, 0], [2, 1, 0], [2, 5, 1], [0, 4, 3], [0, 1, 4], [4, 1, 5], [2, 3, 6], [3, 4, 6], [5, 2, 6], [4, 5, 6]] };
            polyhedra[12] = { vertex: [[-0.669867, 0.334933, -0.529576], [-0.669867, 0.334933, 0.529577], [-0.4043, 1.212901, 0], [-0.334933, -0.669867, -0.529576], [-0.334933, -0.669867, 0.529577], [0.334933, 0.669867, -0.529576], [0.334933, 0.669867, 0.529577], [0.4043, -1.212901, 0], [0.669867, -0.334933, -0.529576], [0.669867, -0.334933, 0.529577]], face: [[8, 9, 7], [6, 5, 2], [3, 8, 7], [5, 0, 2], [4, 3, 7], [0, 1, 2], [9, 4, 7], [1, 6, 2], [9, 8, 5, 6], [8, 3, 0, 5], [3, 4, 1, 0], [4, 9, 6, 1]] };
            polyhedra[13] = { vertex: [[-0.931836, 0.219976, -0.264632], [-0.636706, 0.318353, 0.692816], [-0.613483, -0.735083, -0.264632], [-0.326545, 0.979634, 0], [-0.318353, -0.636706, 0.692816], [-0.159176, 0.477529, -0.856368], [0.159176, -0.477529, -0.856368], [0.318353, 0.636706, 0.692816], [0.326545, -0.979634, 0], [0.613482, 0.735082, -0.264632], [0.636706, -0.318353, 0.692816], [0.931835, -0.219977, -0.264632]], face: [[11, 10, 8], [7, 9, 3], [6, 11, 8], [9, 5, 3], [2, 6, 8], [5, 0, 3], [4, 2, 8], [0, 1, 3], [10, 4, 8], [1, 7, 3], [10, 11, 9, 7], [11, 6, 5, 9], [6, 2, 0, 5], [2, 4, 1, 0], [4, 10, 7, 1]] };
            polyhedra[14] = {
                vertex: [[-0.93465, 0.300459, -0.271185], [-0.838689, -0.260219, -0.516017], [-0.711319, 0.717591, 0.128359], [-0.710334, -0.156922, 0.080946], [-0.599799, 0.556003, -0.725148], [-0.503838, -0.004675, -0.969981], [-0.487004, 0.26021, 0.48049], [-0.460089, -0.750282, -0.512622], [-0.376468, 0.973135, -0.325605], [-0.331735, -0.646985, 0.084342], [-0.254001, 0.831847, 0.530001], [-0.125239, -0.494738, -0.966586], [0.029622, 0.027949, 0.730817], [0.056536, -0.982543, -0.262295], [0.08085, 1.087391, 0.076037], [0.125583, -0.532729, 0.485984], [0.262625, 0.599586, 0.780328], [0.391387, -0.726999, -0.716259], [0.513854, -0.868287, 0.139347], [0.597475, 0.85513, 0.326364], [0.641224, 0.109523, 0.783723], [0.737185, -0.451155, 0.538891], [0.848705, -0.612742, -0.314616], [0.976075, 0.365067, 0.32976], [1.072036, -0.19561, 0.084927]],
                face: [[15, 18, 21], [12, 20, 16], [6, 10, 2], [3, 0, 1], [9, 7, 13], [2, 8, 4, 0], [0, 4, 5, 1], [1, 5, 11, 7], [7, 11, 17, 13], [13, 17, 22, 18], [18, 22, 24, 21], [21, 24, 23, 20], [20, 23, 19, 16], [16, 19, 14, 10], [10, 14, 8, 2], [15, 9, 13, 18], [12, 15, 21, 20], [6, 12, 16, 10], [3, 6, 2, 0], [9, 3, 1, 7], [9, 15, 12, 6, 3], [22, 17, 11, 5, 4, 8, 14, 19, 23, 24]]
            };
            var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
            var size = options.size;
            var sizeX = options.sizeX || size || 1;
            var sizeY = options.sizeY || size || 1;
            var sizeZ = options.sizeZ || size || 1;
            var data = options.custom || polyhedra[type];
            var nbfaces = data.face.length;
            var faceUV = options.faceUV || new Array(nbfaces);
            var faceColors = options.faceColors;
            var flat = (options.flat === undefined) ? true : options.flat;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            var positions = new Array();
            var indices = new Array();
            var normals = new Array();
            var uvs = new Array();
            var colors = new Array();
            var index = 0;
            var faceIdx = 0; // face cursor in the array "indexes"
            var indexes = new Array();
            var i = 0;
            var f = 0;
            var u, v, ang, x, y, tmp;
            // default face colors and UV if undefined
            if (flat) {
                for (f = 0; f < nbfaces; f++) {
                    if (faceColors && faceColors[f] === undefined) {
                        faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
                    }
                    if (faceUV && faceUV[f] === undefined) {
                        faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
                    }
                }
            }
            if (!flat) {
                for (i = 0; i < data.vertex.length; i++) {
                    positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
                    uvs.push(0, 0);
                }
                for (f = 0; f < nbfaces; f++) {
                    for (i = 0; i < data.face[f].length - 2; i++) {
                        indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
                    }
                }
            }
            else {
                for (f = 0; f < nbfaces; f++) {
                    var fl = data.face[f].length; // number of vertices of the current face
                    ang = 2 * Math.PI / fl;
                    x = 0.5 * Math.tan(ang / 2);
                    y = 0.5;
                    // positions, uvs, colors
                    for (i = 0; i < fl; i++) {
                        // positions
                        positions.push(data.vertex[data.face[f][i]][0] * sizeX, data.vertex[data.face[f][i]][1] * sizeY, data.vertex[data.face[f][i]][2] * sizeZ);
                        indexes.push(index);
                        index++;
                        // uvs
                        u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
                        v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
                        uvs.push(u, v);
                        tmp = x * Math.cos(ang) - y * Math.sin(ang);
                        y = x * Math.sin(ang) + y * Math.cos(ang);
                        x = tmp;
                        // colors
                        if (faceColors) {
                            colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
                        }
                    }
                    // indices from indexes
                    for (i = 0; i < fl - 2; i++) {
                        indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
                    }
                    faceIdx += fl;
                }
            }
            VertexData.ComputeNormals(positions, indices, normals);
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            var vertexData = new VertexData();
            vertexData.positions = positions;
            vertexData.indices = indices;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            if (faceColors && flat) {
                vertexData.colors = colors;
            }
            return vertexData;
        };
        // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
        /**
         * Creates the VertexData for a TorusKnot
         * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
          * * radius the radius of the torus knot, optional, default 2
          * * tube the thickness of the tube, optional, default 0.5
          * * radialSegments the number of sides on each tube segments, optional, default 32
          * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
          * * p the number of windings around the z axis, optional,  default 2
          * * q the number of windings around the x axis, optional,  default 3
          * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
          * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
          * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
         * @returns the VertexData of the Torus Knot
         */
        VertexData.CreateTorusKnot = function (options) {
            var indices = new Array();
            var positions = new Array();
            var normals = new Array();
            var uvs = new Array();
            var radius = options.radius || 2;
            var tube = options.tube || 0.5;
            var radialSegments = options.radialSegments || 32;
            var tubularSegments = options.tubularSegments || 32;
            var p = options.p || 2;
            var q = options.q || 3;
            var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            // Helper
            var getPos = function (angle) {
                var cu = Math.cos(angle);
                var su = Math.sin(angle);
                var quOverP = q / p * angle;
                var cs = Math.cos(quOverP);
                var tx = radius * (2 + cs) * 0.5 * cu;
                var ty = radius * (2 + cs) * su * 0.5;
                var tz = radius * Math.sin(quOverP) * 0.5;
                return new BABYLON.Vector3(tx, ty, tz);
            };
            // Vertices
            var i;
            var j;
            for (i = 0; i <= radialSegments; i++) {
                var modI = i % radialSegments;
                var u = modI / radialSegments * 2 * p * Math.PI;
                var p1 = getPos(u);
                var p2 = getPos(u + 0.01);
                var tang = p2.subtract(p1);
                var n = p2.add(p1);
                var bitan = BABYLON.Vector3.Cross(tang, n);
                n = BABYLON.Vector3.Cross(bitan, tang);
                bitan.normalize();
                n.normalize();
                for (j = 0; j < tubularSegments; j++) {
                    var modJ = j % tubularSegments;
                    var v = modJ / tubularSegments * 2 * Math.PI;
                    var cx = -tube * Math.cos(v);
                    var cy = tube * Math.sin(v);
                    positions.push(p1.x + cx * n.x + cy * bitan.x);
                    positions.push(p1.y + cx * n.y + cy * bitan.y);
                    positions.push(p1.z + cx * n.z + cy * bitan.z);
                    uvs.push(i / radialSegments);
                    uvs.push(j / tubularSegments);
                }
            }
            for (i = 0; i < radialSegments; i++) {
                for (j = 0; j < tubularSegments; j++) {
                    var jNext = (j + 1) % tubularSegments;
                    var a = i * tubularSegments + j;
                    var b = (i + 1) * tubularSegments + j;
                    var c = (i + 1) * tubularSegments + jNext;
                    var d = i * tubularSegments + jNext;
                    indices.push(d);
                    indices.push(b);
                    indices.push(a);
                    indices.push(d);
                    indices.push(c);
                    indices.push(b);
                }
            }
            // Normals
            VertexData.ComputeNormals(positions, indices, normals);
            // Sides
            VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
            // Result
            var vertexData = new VertexData();
            vertexData.indices = indices;
            vertexData.positions = positions;
            vertexData.normals = normals;
            vertexData.uvs = uvs;
            return vertexData;
        };
        // Tools
        /**
         * Compute normals for given positions and indices
         * @param positions an array of vertex positions, [...., x, y, z, ......]
         * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
         * @param normals an array of vertex normals, [...., x, y, z, ......]
         * @param options an object used to set the following optional parameters for the TorusKnot, optional
          * * facetNormals : optional array of facet normals (vector3)
          * * facetPositions : optional array of facet positions (vector3)
          * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
          * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
          * * bInfo : optional bounding info, required for facetPartitioning computation
          * * bbSize : optional bounding box size data, required for facetPartitioning computation
          * * subDiv : optional partitioning data about subdivsions on  each axis (int), required for facetPartitioning computation
          * * useRightHandedSystem: optional boolean to for right handed system computation
          * * depthSort : optional boolean to enable the facet depth sort computation
          * * distanceTo : optional Vector3 to compute the facet depth from this location
          * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
         */
        VertexData.ComputeNormals = function (positions, indices, normals, options) {
            // temporary scalar variables
            var index = 0; // facet index
            var p1p2x = 0.0; // p1p2 vector x coordinate
            var p1p2y = 0.0; // p1p2 vector y coordinate
            var p1p2z = 0.0; // p1p2 vector z coordinate
            var p3p2x = 0.0; // p3p2 vector x coordinate
            var p3p2y = 0.0; // p3p2 vector y coordinate
            var p3p2z = 0.0; // p3p2 vector z coordinate
            var faceNormalx = 0.0; // facet normal x coordinate
            var faceNormaly = 0.0; // facet normal y coordinate
            var faceNormalz = 0.0; // facet normal z coordinate
            var length = 0.0; // facet normal length before normalization
            var v1x = 0; // vector1 x index in the positions array
            var v1y = 0; // vector1 y index in the positions array
            var v1z = 0; // vector1 z index in the positions array
            var v2x = 0; // vector2 x index in the positions array
            var v2y = 0; // vector2 y index in the positions array
            var v2z = 0; // vector2 z index in the positions array
            var v3x = 0; // vector3 x index in the positions array
            var v3y = 0; // vector3 y index in the positions array
            var v3z = 0; // vector3 z index in the positions array
            var computeFacetNormals = false;
            var computeFacetPositions = false;
            var computeFacetPartitioning = false;
            var computeDepthSort = false;
            var faceNormalSign = 1;
            var ratio = 0;
            var distanceTo = null;
            if (options) {
                computeFacetNormals = (options.facetNormals) ? true : false;
                computeFacetPositions = (options.facetPositions) ? true : false;
                computeFacetPartitioning = (options.facetPartitioning) ? true : false;
                faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
                ratio = options.ratio || 0;
                computeDepthSort = (options.depthSort) ? true : false;
                distanceTo = (options.distanceTo);
                if (computeDepthSort) {
                    if (distanceTo === undefined) {
                        distanceTo = BABYLON.Vector3.Zero();
                    }
                    var depthSortedFacets = options.depthSortedFacets;
                }
            }
            // facetPartitioning reinit if needed
            var xSubRatio = 0;
            var ySubRatio = 0;
            var zSubRatio = 0;
            var subSq = 0;
            if (computeFacetPartitioning && options && options.bbSize) {
                var ox = 0; // X partitioning index for facet position
                var oy = 0; // Y partinioning index for facet position
                var oz = 0; // Z partinioning index for facet position
                var b1x = 0; // X partitioning index for facet v1 vertex
                var b1y = 0; // Y partitioning index for facet v1 vertex
                var b1z = 0; // z partitioning index for facet v1 vertex
                var b2x = 0; // X partitioning index for facet v2 vertex
                var b2y = 0; // Y partitioning index for facet v2 vertex
                var b2z = 0; // Z partitioning index for facet v2 vertex
                var b3x = 0; // X partitioning index for facet v3 vertex
                var b3y = 0; // Y partitioning index for facet v3 vertex
                var b3z = 0; // Z partitioning index for facet v3 vertex
                var block_idx_o = 0; // facet barycenter block index
                var block_idx_v1 = 0; // v1 vertex block index
                var block_idx_v2 = 0; // v2 vertex block index
                var block_idx_v3 = 0; // v3 vertex block index
                var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
                bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
                xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
                ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
                zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
                subSq = options.subDiv.max * options.subDiv.max;
                options.facetPartitioning.length = 0;
            }
            // reset the normals
            for (index = 0; index < positions.length; index++) {
                normals[index] = 0.0;
            }
            // Loop : 1 indice triplet = 1 facet
            var nbFaces = (indices.length / 3) | 0;
            for (index = 0; index < nbFaces; index++) {
                // get the indexes of the coordinates of each vertex of the facet
                v1x = indices[index * 3] * 3;
                v1y = v1x + 1;
                v1z = v1x + 2;
                v2x = indices[index * 3 + 1] * 3;
                v2y = v2x + 1;
                v2z = v2x + 2;
                v3x = indices[index * 3 + 2] * 3;
                v3y = v3x + 1;
                v3z = v3x + 2;
                p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
                p1p2y = positions[v1y] - positions[v2y];
                p1p2z = positions[v1z] - positions[v2z];
                p3p2x = positions[v3x] - positions[v2x];
                p3p2y = positions[v3y] - positions[v2y];
                p3p2z = positions[v3z] - positions[v2z];
                // compute the face normal with the cross product
                faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
                faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
                faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
                // normalize this normal and store it in the array facetData
                length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
                length = (length === 0) ? 1.0 : length;
                faceNormalx /= length;
                faceNormaly /= length;
                faceNormalz /= length;
                if (computeFacetNormals && options) {
                    options.facetNormals[index].x = faceNormalx;
                    options.facetNormals[index].y = faceNormaly;
                    options.facetNormals[index].z = faceNormalz;
                }
                if (computeFacetPositions && options) {
                    // compute and the facet barycenter coordinates in the array facetPositions
                    options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
                    options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
                    options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
                }
                if (computeFacetPartitioning && options) {
                    // store the facet indexes in arrays in the main facetPartitioning array :
                    // compute each facet vertex (+ facet barycenter) index in the partiniong array
                    ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
                    oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
                    oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
                    b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
                    b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
                    b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
                    b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
                    b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
                    b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
                    b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
                    b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
                    b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
                    block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
                    block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
                    block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
                    block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
                    options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
                    options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
                    options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
                    options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
                    // push each facet index in each block containing the vertex
                    options.facetPartitioning[block_idx_v1].push(index);
                    if (block_idx_v2 != block_idx_v1) {
                        options.facetPartitioning[block_idx_v2].push(index);
                    }
                    if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
                        options.facetPartitioning[block_idx_v3].push(index);
                    }
                    if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
                        options.facetPartitioning[block_idx_o].push(index);
                    }
                }
                if (computeDepthSort && options && options.facetPositions) {
                    var dsf = depthSortedFacets[index];
                    dsf.ind = index * 3;
                    dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
                }
                // compute the normals anyway
                normals[v1x] += faceNormalx; // accumulate all the normals per face
                normals[v1y] += faceNormaly;
                normals[v1z] += faceNormalz;
                normals[v2x] += faceNormalx;
                normals[v2y] += faceNormaly;
                normals[v2z] += faceNormalz;
                normals[v3x] += faceNormalx;
                normals[v3y] += faceNormaly;
                normals[v3z] += faceNormalz;
            }
            // last normalization of each normal
            for (index = 0; index < normals.length / 3; index++) {
                faceNormalx = normals[index * 3];
                faceNormaly = normals[index * 3 + 1];
                faceNormalz = normals[index * 3 + 2];
                length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
                length = (length === 0) ? 1.0 : length;
                faceNormalx /= length;
                faceNormaly /= length;
                faceNormalz /= length;
                normals[index * 3] = faceNormalx;
                normals[index * 3 + 1] = faceNormaly;
                normals[index * 3 + 2] = faceNormalz;
            }
        };
        VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
            var li = indices.length;
            var ln = normals.length;
            var i;
            var n;
            sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
            switch (sideOrientation) {
                case BABYLON.Mesh.FRONTSIDE:
                    // nothing changed
                    break;
                case BABYLON.Mesh.BACKSIDE:
                    var tmp;
                    // indices
                    for (i = 0; i < li; i += 3) {
                        tmp = indices[i];
                        indices[i] = indices[i + 2];
                        indices[i + 2] = tmp;
                    }
                    // normals
                    for (n = 0; n < ln; n++) {
                        normals[n] = -normals[n];
                    }
                    break;
                case BABYLON.Mesh.DOUBLESIDE:
                    // positions
                    var lp = positions.length;
                    var l = lp / 3;
                    for (var p = 0; p < lp; p++) {
                        positions[lp + p] = positions[p];
                    }
                    // indices
                    for (i = 0; i < li; i += 3) {
                        indices[i + li] = indices[i + 2] + l;
                        indices[i + 1 + li] = indices[i + 1] + l;
                        indices[i + 2 + li] = indices[i] + l;
                    }
                    // normals
                    for (n = 0; n < ln; n++) {
                        normals[ln + n] = -normals[n];
                    }
                    // uvs
                    var lu = uvs.length;
                    var u = 0;
                    for (u = 0; u < lu; u++) {
                        uvs[u + lu] = uvs[u];
                    }
                    frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
                    backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
                    u = 0;
                    for (i = 0; i < lu / 2; i++) {
                        uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
                        uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
                        uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
                        uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
                        u += 2;
                    }
                    break;
            }
        };
        /**
         * Applies VertexData created from the imported parameters to the geometry
         * @param parsedVertexData the parsed data from an imported file
         * @param geometry the geometry to apply the VertexData to
         */
        VertexData.ImportVertexData = function (parsedVertexData, geometry) {
            var vertexData = new VertexData();
            // positions
            var positions = parsedVertexData.positions;
            if (positions) {
                vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
            }
            // normals
            var normals = parsedVertexData.normals;
            if (normals) {
                vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
            }
            // tangents
            var tangents = parsedVertexData.tangents;
            if (tangents) {
                vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
            }
            // uvs
            var uvs = parsedVertexData.uvs;
            if (uvs) {
                vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
            }
            // uv2s
            var uv2s = parsedVertexData.uv2s;
            if (uv2s) {
                vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
            }
            // uv3s
            var uv3s = parsedVertexData.uv3s;
            if (uv3s) {
                vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
            }
            // uv4s
            var uv4s = parsedVertexData.uv4s;
            if (uv4s) {
                vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
            }
            // uv5s
            var uv5s = parsedVertexData.uv5s;
            if (uv5s) {
                vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
            }
            // uv6s
            var uv6s = parsedVertexData.uv6s;
            if (uv6s) {
                vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
            }
            // colors
            var colors = parsedVertexData.colors;
            if (colors) {
                vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
            }
            // matricesIndices
            var matricesIndices = parsedVertexData.matricesIndices;
            if (matricesIndices) {
                vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
            }
            // matricesWeights
            var matricesWeights = parsedVertexData.matricesWeights;
            if (matricesWeights) {
                vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
            }
            // indices
            var indices = parsedVertexData.indices;
            if (indices) {
                vertexData.indices = indices;
            }
            geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
        };
        return VertexData;
    }());
    BABYLON.VertexData = VertexData;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.mesh.vertexData.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store geometry data (vertex buffers + index buffer)
     */
    var Geometry = /** @class */ (function () {
        /**
         * Creates a new geometry
         * @param id defines the unique ID
         * @param scene defines the hosting scene
         * @param vertexData defines the VertexData used to get geometry data
         * @param updatable defines if geometry must be updatable (false by default)
         * @param mesh defines the mesh that will be associated with the geometry
         */
        function Geometry(id, scene, vertexData, updatable, mesh) {
            if (updatable === void 0) { updatable = false; }
            if (mesh === void 0) { mesh = null; }
            /**
             * Gets the delay loading state of the geometry (none by default which means not delayed)
             */
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this._totalVertices = 0;
            this._isDisposed = false;
            this._indexBufferIsUpdatable = false;
            this.id = id;
            this._engine = scene.getEngine();
            this._meshes = [];
            this._scene = scene;
            //Init vertex buffer cache
            this._vertexBuffers = {};
            this._indices = [];
            this._updatable = updatable;
            // vertexData
            if (vertexData) {
                this.setAllVerticesData(vertexData, updatable);
            }
            else {
                this._totalVertices = 0;
                this._indices = [];
            }
            if (this._engine.getCaps().vertexArrayObject) {
                this._vertexArrayObjects = {};
            }
            // applyToMesh
            if (mesh) {
                if (mesh.getClassName() === "LinesMesh") {
                    this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
                    this._updateExtend();
                }
                this.applyToMesh(mesh);
                mesh.computeWorldMatrix(true);
            }
        }
        Object.defineProperty(Geometry.prototype, "boundingBias", {
            /**
             *  Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
             */
            get: function () {
                return this._boundingBias;
            },
            /**
             *  Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
             */
            set: function (value) {
                if (this._boundingBias) {
                    if (this._boundingBias.equals(value)) {
                        return;
                    }
                    this._boundingBias.copyFrom(value);
                }
                else {
                    this._boundingBias = value.clone();
                }
                this._updateBoundingInfo(true, null);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Static function used to attach a new empty geometry to a mesh
         * @param mesh defines the mesh to attach the geometry to
         * @returns the new Geometry
         */
        Geometry.CreateGeometryForMesh = function (mesh) {
            var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
            geometry.applyToMesh(mesh);
            return geometry;
        };
        Object.defineProperty(Geometry.prototype, "extend", {
            /**
             * Gets the current extend of the geometry
             */
            get: function () {
                return this._extend;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the hosting scene
         * @returns the hosting Scene
         */
        Geometry.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Gets the hosting engine
         * @returns the hosting Engine
         */
        Geometry.prototype.getEngine = function () {
            return this._engine;
        };
        /**
         * Defines if the geometry is ready to use
         * @returns true if the geometry is ready to be used
         */
        Geometry.prototype.isReady = function () {
            return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
        };
        Object.defineProperty(Geometry.prototype, "doNotSerialize", {
            /**
             * Gets a value indicating that the geometry should not be serialized
             */
            get: function () {
                for (var index = 0; index < this._meshes.length; index++) {
                    if (!this._meshes[index].doNotSerialize) {
                        return false;
                    }
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Geometry.prototype._rebuild = function () {
            if (this._vertexArrayObjects) {
                this._vertexArrayObjects = {};
            }
            // Index buffer
            if (this._meshes.length !== 0 && this._indices) {
                this._indexBuffer = this._engine.createIndexBuffer(this._indices);
            }
            // Vertex buffers
            for (var key in this._vertexBuffers) {
                var vertexBuffer = this._vertexBuffers[key];
                vertexBuffer._rebuild();
            }
        };
        /**
         * Affects all geometry data in one call
         * @param vertexData defines the geometry data
         * @param updatable defines if the geometry must be flagged as updatable (false as default)
         */
        Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
            vertexData.applyToGeometry(this, updatable);
            this.notifyUpdate();
        };
        /**
         * Set specific vertex data
         * @param kind defines the data kind (Position, normal, etc...)
         * @param data defines the vertex data to use
         * @param updatable defines if the vertex must be flagged as updatable (false as default)
         * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
         */
        Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
            if (updatable === void 0) { updatable = false; }
            var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
            this.setVerticesBuffer(buffer);
        };
        /**
         * Removes a specific vertex data
         * @param kind defines the data kind (Position, normal, etc...)
         */
        Geometry.prototype.removeVerticesData = function (kind) {
            if (this._vertexBuffers[kind]) {
                this._vertexBuffers[kind].dispose();
                delete this._vertexBuffers[kind];
            }
        };
        /**
         * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
         * @param buffer defines the vertex buffer to use
         * @param totalVertices defines the total number of vertices for position kind (could be null)
         */
        Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
            if (totalVertices === void 0) { totalVertices = null; }
            var kind = buffer.getKind();
            if (this._vertexBuffers[kind]) {
                this._vertexBuffers[kind].dispose();
            }
            this._vertexBuffers[kind] = buffer;
            if (kind === BABYLON.VertexBuffer.PositionKind) {
                var data = buffer.getData();
                if (totalVertices != null) {
                    this._totalVertices = totalVertices;
                }
                else {
                    if (data != null) {
                        this._totalVertices = data.length / (buffer.byteStride / 4);
                    }
                }
                this._updateExtend(data);
                this._resetPointsArrayCache();
                var meshes = this._meshes;
                var numOfMeshes = meshes.length;
                for (var index = 0; index < numOfMeshes; index++) {
                    var mesh = meshes[index];
                    mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
                    mesh._createGlobalSubMesh(false);
                    mesh.computeWorldMatrix(true);
                }
            }
            this.notifyUpdate(kind);
            if (this._vertexArrayObjects) {
                this._disposeVertexArrayObjects();
                this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
            }
        };
        /**
         * Update a specific vertex buffer
         * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
         * It will do nothing if the buffer is not updatable
         * @param kind defines the data kind (Position, normal, etc...)
         * @param data defines the data to use
         * @param offset defines the offset in the target buffer where to store the data
         * @param useBytes set to true if the offset is in bytes
         */
        Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
            if (useBytes === void 0) { useBytes = false; }
            var vertexBuffer = this.getVertexBuffer(kind);
            if (!vertexBuffer) {
                return;
            }
            vertexBuffer.updateDirectly(data, offset, useBytes);
            this.notifyUpdate(kind);
        };
        /**
         * Update a specific vertex buffer
         * This function will create a new buffer if the current one is not updatable
         * @param kind defines the data kind (Position, normal, etc...)
         * @param data defines the data to use
         * @param updateExtends defines if the geometry extends must be recomputed (false by default)
         */
        Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
            if (updateExtends === void 0) { updateExtends = false; }
            var vertexBuffer = this.getVertexBuffer(kind);
            if (!vertexBuffer) {
                return;
            }
            vertexBuffer.update(data);
            if (kind === BABYLON.VertexBuffer.PositionKind) {
                this._updateBoundingInfo(updateExtends, data);
            }
            this.notifyUpdate(kind);
        };
        Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
            if (updateExtends) {
                this._updateExtend(data);
            }
            var meshes = this._meshes;
            var numOfMeshes = meshes.length;
            this._resetPointsArrayCache();
            for (var index = 0; index < numOfMeshes; index++) {
                var mesh = meshes[index];
                if (updateExtends) {
                    mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
                    for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
                        var subMesh = mesh.subMeshes[subIndex];
                        subMesh.refreshBoundingInfo();
                    }
                }
            }
        };
        /** @hidden */
        Geometry.prototype._bind = function (effect, indexToBind) {
            if (!effect) {
                return;
            }
            if (indexToBind === undefined) {
                indexToBind = this._indexBuffer;
            }
            var vbs = this.getVertexBuffers();
            if (!vbs) {
                return;
            }
            if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
                this._engine.bindBuffers(vbs, indexToBind, effect);
                return;
            }
            // Using VAO
            if (!this._vertexArrayObjects[effect.key]) {
                this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
            }
            this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
        };
        /**
         * Gets total number of vertices
         * @returns the total number of vertices
         */
        Geometry.prototype.getTotalVertices = function () {
            if (!this.isReady()) {
                return 0;
            }
            return this._totalVertices;
        };
        /**
         * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
         * @param kind defines the data kind (Position, normal, etc...)
         * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
         * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
         * @returns a float array containing vertex data
         */
        Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
            var vertexBuffer = this.getVertexBuffer(kind);
            if (!vertexBuffer) {
                return null;
            }
            var data = vertexBuffer.getData();
            if (!data) {
                return null;
            }
            var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
            var count = this._totalVertices * vertexBuffer.getSize();
            if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
                var copy_1 = new Array(count);
                vertexBuffer.forEach(count, function (value, index) {
                    copy_1[index] = value;
                });
                return copy_1;
            }
            if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
                if (data instanceof Array) {
                    var offset = vertexBuffer.byteOffset / 4;
                    return BABYLON.Tools.Slice(data, offset, offset + count);
                }
                else if (data instanceof ArrayBuffer) {
                    return new Float32Array(data, vertexBuffer.byteOffset, count);
                }
                else {
                    var offset = data.byteOffset + vertexBuffer.byteOffset;
                    if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
                        var result = new Float32Array(count);
                        var source = new Float32Array(data.buffer, offset, count);
                        result.set(source);
                        return result;
                    }
                    return new Float32Array(data.buffer, offset, count);
                }
            }
            if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
                return BABYLON.Tools.Slice(data);
            }
            return data;
        };
        /**
         * Returns a boolean defining if the vertex data for the requested `kind` is updatable
         * @param kind defines the data kind (Position, normal, etc...)
         * @returns true if the vertex buffer with the specified kind is updatable
         */
        Geometry.prototype.isVertexBufferUpdatable = function (kind) {
            var vb = this._vertexBuffers[kind];
            if (!vb) {
                return false;
            }
            return vb.isUpdatable();
        };
        /**
         * Gets a specific vertex buffer
         * @param kind defines the data kind (Position, normal, etc...)
         * @returns a VertexBuffer
         */
        Geometry.prototype.getVertexBuffer = function (kind) {
            if (!this.isReady()) {
                return null;
            }
            return this._vertexBuffers[kind];
        };
        /**
         * Returns all vertex buffers
         * @return an object holding all vertex buffers indexed by kind
         */
        Geometry.prototype.getVertexBuffers = function () {
            if (!this.isReady()) {
                return null;
            }
            return this._vertexBuffers;
        };
        /**
         * Gets a boolean indicating if specific vertex buffer is present
         * @param kind defines the data kind (Position, normal, etc...)
         * @returns true if data is present
         */
        Geometry.prototype.isVerticesDataPresent = function (kind) {
            if (!this._vertexBuffers) {
                if (this._delayInfo) {
                    return this._delayInfo.indexOf(kind) !== -1;
                }
                return false;
            }
            return this._vertexBuffers[kind] !== undefined;
        };
        /**
         * Gets a list of all attached data kinds (Position, normal, etc...)
         * @returns a list of string containing all kinds
         */
        Geometry.prototype.getVerticesDataKinds = function () {
            var result = [];
            var kind;
            if (!this._vertexBuffers && this._delayInfo) {
                for (kind in this._delayInfo) {
                    result.push(kind);
                }
            }
            else {
                for (kind in this._vertexBuffers) {
                    result.push(kind);
                }
            }
            return result;
        };
        /**
         * Update index buffer
         * @param indices defines the indices to store in the index buffer
         * @param offset defines the offset in the target buffer where to store the data
         */
        Geometry.prototype.updateIndices = function (indices, offset) {
            if (!this._indexBuffer) {
                return;
            }
            if (!this._indexBufferIsUpdatable) {
                this.setIndices(indices, null, true);
            }
            else {
                this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
            }
        };
        /**
         * Creates a new index buffer
         * @param indices defines the indices to store in the index buffer
         * @param totalVertices defines the total number of vertices (could be null)
         * @param updatable defines if the index buffer must be flagged as updatable (false by default)
         */
        Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
            if (totalVertices === void 0) { totalVertices = null; }
            if (updatable === void 0) { updatable = false; }
            if (this._indexBuffer) {
                this._engine._releaseBuffer(this._indexBuffer);
            }
            this._disposeVertexArrayObjects();
            this._indices = indices;
            this._indexBufferIsUpdatable = updatable;
            if (this._meshes.length !== 0 && this._indices) {
                this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
            }
            if (totalVertices != undefined) { // including null and undefined
                this._totalVertices = totalVertices;
            }
            var meshes = this._meshes;
            var numOfMeshes = meshes.length;
            for (var index = 0; index < numOfMeshes; index++) {
                meshes[index]._createGlobalSubMesh(true);
            }
            this.notifyUpdate();
        };
        /**
         * Return the total number of indices
         * @returns the total number of indices
         */
        Geometry.prototype.getTotalIndices = function () {
            if (!this.isReady()) {
                return 0;
            }
            return this._indices.length;
        };
        /**
         * Gets the index buffer array
         * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
         * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
         * @returns the index buffer array
         */
        Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
            if (!this.isReady()) {
                return null;
            }
            var orig = this._indices;
            if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
                return orig;
            }
            else {
                var len = orig.length;
                var copy = [];
                for (var i = 0; i < len; i++) {
                    copy.push(orig[i]);
                }
                return copy;
            }
        };
        /**
         * Gets the index buffer
         * @return the index buffer
         */
        Geometry.prototype.getIndexBuffer = function () {
            if (!this.isReady()) {
                return null;
            }
            return this._indexBuffer;
        };
        /** @hidden */
        Geometry.prototype._releaseVertexArrayObject = function (effect) {
            if (effect === void 0) { effect = null; }
            if (!effect || !this._vertexArrayObjects) {
                return;
            }
            if (this._vertexArrayObjects[effect.key]) {
                this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
                delete this._vertexArrayObjects[effect.key];
            }
        };
        /**
         * Release the associated resources for a specific mesh
         * @param mesh defines the source mesh
         * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
         */
        Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
            var meshes = this._meshes;
            var index = meshes.indexOf(mesh);
            if (index === -1) {
                return;
            }
            meshes.splice(index, 1);
            mesh._geometry = null;
            if (meshes.length === 0 && shouldDispose) {
                this.dispose();
            }
        };
        /**
         * Apply current geometry to a given mesh
         * @param mesh defines the mesh to apply geometry to
         */
        Geometry.prototype.applyToMesh = function (mesh) {
            if (mesh._geometry === this) {
                return;
            }
            var previousGeometry = mesh._geometry;
            if (previousGeometry) {
                previousGeometry.releaseForMesh(mesh);
            }
            var meshes = this._meshes;
            // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
            mesh._geometry = this;
            this._scene.pushGeometry(this);
            meshes.push(mesh);
            if (this.isReady()) {
                this._applyToMesh(mesh);
            }
            else {
                mesh._boundingInfo = this._boundingInfo;
            }
        };
        Geometry.prototype._updateExtend = function (data) {
            if (data === void 0) { data = null; }
            if (!data) {
                data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            }
            this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
        };
        Geometry.prototype._applyToMesh = function (mesh) {
            var numOfMeshes = this._meshes.length;
            // vertexBuffers
            for (var kind in this._vertexBuffers) {
                if (numOfMeshes === 1) {
                    this._vertexBuffers[kind].create();
                }
                var buffer = this._vertexBuffers[kind].getBuffer();
                if (buffer) {
                    buffer.references = numOfMeshes;
                }
                if (kind === BABYLON.VertexBuffer.PositionKind) {
                    if (!this._extend) {
                        this._updateExtend();
                    }
                    mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
                    mesh._createGlobalSubMesh(false);
                    //bounding info was just created again, world matrix should be applied again.
                    mesh._updateBoundingInfo();
                }
            }
            // indexBuffer
            if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
                this._indexBuffer = this._engine.createIndexBuffer(this._indices);
            }
            if (this._indexBuffer) {
                this._indexBuffer.references = numOfMeshes;
            }
            // morphTargets
            mesh._syncGeometryWithMorphTargetManager();
        };
        Geometry.prototype.notifyUpdate = function (kind) {
            if (this.onGeometryUpdated) {
                this.onGeometryUpdated(this, kind);
            }
            for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                mesh._markSubMeshesAsAttributesDirty();
            }
        };
        /**
         * Load the geometry if it was flagged as delay loaded
         * @param scene defines the hosting scene
         * @param onLoaded defines a callback called when the geometry is loaded
         */
        Geometry.prototype.load = function (scene, onLoaded) {
            if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
                return;
            }
            if (this.isReady()) {
                if (onLoaded) {
                    onLoaded();
                }
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
            this._queueLoad(scene, onLoaded);
        };
        Geometry.prototype._queueLoad = function (scene, onLoaded) {
            var _this = this;
            if (!this.delayLoadingFile) {
                return;
            }
            scene._addPendingData(this);
            scene._loadFile(this.delayLoadingFile, function (data) {
                if (!_this._delayLoadingFunction) {
                    return;
                }
                _this._delayLoadingFunction(JSON.parse(data), _this);
                _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
                _this._delayInfo = [];
                scene._removePendingData(_this);
                var meshes = _this._meshes;
                var numOfMeshes = meshes.length;
                for (var index = 0; index < numOfMeshes; index++) {
                    _this._applyToMesh(meshes[index]);
                }
                if (onLoaded) {
                    onLoaded();
                }
            }, undefined, true);
        };
        /**
         * Invert the geometry to move from a right handed system to a left handed one.
         */
        Geometry.prototype.toLeftHanded = function () {
            // Flip faces
            var tIndices = this.getIndices(false);
            if (tIndices != null && tIndices.length > 0) {
                for (var i = 0; i < tIndices.length; i += 3) {
                    var tTemp = tIndices[i + 0];
                    tIndices[i + 0] = tIndices[i + 2];
                    tIndices[i + 2] = tTemp;
                }
                this.setIndices(tIndices);
            }
            // Negate position.z
            var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
            if (tPositions != null && tPositions.length > 0) {
                for (var i = 0; i < tPositions.length; i += 3) {
                    tPositions[i + 2] = -tPositions[i + 2];
                }
                this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
            }
            // Negate normal.z
            var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
            if (tNormals != null && tNormals.length > 0) {
                for (var i = 0; i < tNormals.length; i += 3) {
                    tNormals[i + 2] = -tNormals[i + 2];
                }
                this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
            }
        };
        // Cache
        /** @hidden */
        Geometry.prototype._resetPointsArrayCache = function () {
            this._positions = null;
        };
        /** @hidden */
        Geometry.prototype._generatePointsArray = function () {
            if (this._positions) {
                return true;
            }
            var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!data || data.length === 0) {
                return false;
            }
            this._positions = [];
            for (var index = 0; index < data.length; index += 3) {
                this._positions.push(BABYLON.Vector3.FromArray(data, index));
            }
            return true;
        };
        /**
         * Gets a value indicating if the geometry is disposed
         * @returns true if the geometry was disposed
         */
        Geometry.prototype.isDisposed = function () {
            return this._isDisposed;
        };
        Geometry.prototype._disposeVertexArrayObjects = function () {
            if (this._vertexArrayObjects) {
                for (var kind in this._vertexArrayObjects) {
                    this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
                }
                this._vertexArrayObjects = {};
            }
        };
        /**
         * Free all associated resources
         */
        Geometry.prototype.dispose = function () {
            var meshes = this._meshes;
            var numOfMeshes = meshes.length;
            var index;
            for (index = 0; index < numOfMeshes; index++) {
                this.releaseForMesh(meshes[index]);
            }
            this._meshes = [];
            this._disposeVertexArrayObjects();
            for (var kind in this._vertexBuffers) {
                this._vertexBuffers[kind].dispose();
            }
            this._vertexBuffers = {};
            this._totalVertices = 0;
            if (this._indexBuffer) {
                this._engine._releaseBuffer(this._indexBuffer);
            }
            this._indexBuffer = null;
            this._indices = [];
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
            this.delayLoadingFile = null;
            this._delayLoadingFunction = null;
            this._delayInfo = [];
            this._boundingInfo = null;
            this._scene.removeGeometry(this);
            this._isDisposed = true;
        };
        /**
         * Clone the current geometry into a new geometry
         * @param id defines the unique ID of the new geometry
         * @returns a new geometry object
         */
        Geometry.prototype.copy = function (id) {
            var vertexData = new BABYLON.VertexData();
            vertexData.indices = [];
            var indices = this.getIndices();
            if (indices) {
                for (var index = 0; index < indices.length; index++) {
                    vertexData.indices.push(indices[index]);
                }
            }
            var updatable = false;
            var stopChecking = false;
            var kind;
            for (kind in this._vertexBuffers) {
                // using slice() to make a copy of the array and not just reference it
                var data = this.getVerticesData(kind);
                if (data instanceof Float32Array) {
                    vertexData.set(new Float32Array(data), kind);
                }
                else {
                    vertexData.set(data.slice(0), kind);
                }
                if (!stopChecking) {
                    var vb = this.getVertexBuffer(kind);
                    if (vb) {
                        updatable = vb.isUpdatable();
                        stopChecking = !updatable;
                    }
                }
            }
            var geometry = new Geometry(id, this._scene, vertexData, updatable);
            geometry.delayLoadState = this.delayLoadState;
            geometry.delayLoadingFile = this.delayLoadingFile;
            geometry._delayLoadingFunction = this._delayLoadingFunction;
            for (kind in this._delayInfo) {
                geometry._delayInfo = geometry._delayInfo || [];
                geometry._delayInfo.push(kind);
            }
            // Bounding info
            geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
            return geometry;
        };
        /**
         * Serialize the current geometry info (and not the vertices data) into a JSON object
         * @return a JSON representation of the current geometry data (without the vertices data)
         */
        Geometry.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.id = this.id;
            serializationObject.updatable = this._updatable;
            if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
                serializationObject.tags = BABYLON.Tags.GetTags(this);
            }
            return serializationObject;
        };
        Geometry.prototype.toNumberArray = function (origin) {
            if (Array.isArray(origin)) {
                return origin;
            }
            else {
                return Array.prototype.slice.call(origin);
            }
        };
        /**
         * Serialize all vertices data into a JSON oject
         * @returns a JSON representation of the current geometry data
         */
        Geometry.prototype.serializeVerticeData = function () {
            var serializationObject = this.serialize();
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
                serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
                    serializationObject.positions._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
                    serializationObject.normals._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
                serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
                    serializationObject.tangets._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
                    serializationObject.uvs._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
                    serializationObject.uv2s._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
                serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
                    serializationObject.uv3s._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
                serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
                    serializationObject.uv4s._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
                serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
                    serializationObject.uv5s._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
                serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
                    serializationObject.uv6s._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
                    serializationObject.colors._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
                serializationObject.matricesIndices._isExpanded = true;
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
                    serializationObject.matricesIndices._updatable = true;
                }
            }
            if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
                if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
                    serializationObject.matricesWeights._updatable = true;
                }
            }
            serializationObject.indices = this.toNumberArray(this.getIndices());
            return serializationObject;
        };
        // Statics
        /**
         * Extracts a clone of a mesh geometry
         * @param mesh defines the source mesh
         * @param id defines the unique ID of the new geometry object
         * @returns the new geometry object
         */
        Geometry.ExtractFromMesh = function (mesh, id) {
            var geometry = mesh._geometry;
            if (!geometry) {
                return null;
            }
            return geometry.copy(id);
        };
        /**
         * You should now use Tools.RandomId(), this method is still here for legacy reasons.
         * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
         * Be aware Math.random() could cause collisions, but:
         * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
         * @returns a string containing a new GUID
         */
        Geometry.RandomId = function () {
            return BABYLON.Tools.RandomId();
        };
        /** @hidden */
        Geometry._ImportGeometry = function (parsedGeometry, mesh) {
            var scene = mesh.getScene();
            // Geometry
            var geometryId = parsedGeometry.geometryId;
            if (geometryId) {
                var geometry = scene.getGeometryByID(geometryId);
                if (geometry) {
                    geometry.applyToMesh(mesh);
                }
            }
            else if (parsedGeometry instanceof ArrayBuffer) {
                var binaryInfo = mesh._binaryInfo;
                if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
                    var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
                }
                if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
                    var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
                }
                if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
                    var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
                }
                if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
                    var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
                }
                if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
                    var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
                }
                if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
                    var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
                }
                if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
                    var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
                }
                if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
                    var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
                }
                if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
                    var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
                }
                if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
                    var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
                }
                if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
                    var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
                    var floatIndices = [];
                    for (var i = 0; i < matricesIndicesData.length; i++) {
                        var index = matricesIndicesData[i];
                        floatIndices.push(index & 0x000000FF);
                        floatIndices.push((index & 0x0000FF00) >> 8);
                        floatIndices.push((index & 0x00FF0000) >> 16);
                        floatIndices.push(index >> 24);
                    }
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
                }
                if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
                    var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
                }
                if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
                    var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
                    mesh.setIndices(indicesData, null);
                }
                if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
                    var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
                    mesh.subMeshes = [];
                    for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
                        var materialIndex = subMeshesData[(i * 5) + 0];
                        var verticesStart = subMeshesData[(i * 5) + 1];
                        var verticesCount = subMeshesData[(i * 5) + 2];
                        var indexStart = subMeshesData[(i * 5) + 3];
                        var indexCount = subMeshesData[(i * 5) + 4];
                        BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
                    }
                }
            }
            else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
                mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
                mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
                if (parsedGeometry.tangents) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
                }
                if (parsedGeometry.uvs) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
                }
                if (parsedGeometry.uvs2) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
                }
                if (parsedGeometry.uvs3) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
                }
                if (parsedGeometry.uvs4) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
                }
                if (parsedGeometry.uvs5) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
                }
                if (parsedGeometry.uvs6) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
                }
                if (parsedGeometry.colors) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
                }
                if (parsedGeometry.matricesIndices) {
                    if (!parsedGeometry.matricesIndices._isExpanded) {
                        var floatIndices = [];
                        for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
                            var matricesIndex = parsedGeometry.matricesIndices[i];
                            floatIndices.push(matricesIndex & 0x000000FF);
                            floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
                            floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
                            floatIndices.push(matricesIndex >> 24);
                        }
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
                    }
                    else {
                        delete parsedGeometry.matricesIndices._isExpanded;
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
                    }
                }
                if (parsedGeometry.matricesIndicesExtra) {
                    if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
                        var floatIndices = [];
                        for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
                            var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
                            floatIndices.push(matricesIndex & 0x000000FF);
                            floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
                            floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
                            floatIndices.push(matricesIndex >> 24);
                        }
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
                    }
                    else {
                        delete parsedGeometry.matricesIndices._isExpanded;
                        mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
                    }
                }
                if (parsedGeometry.matricesWeights) {
                    Geometry._CleanMatricesWeights(parsedGeometry, mesh);
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
                }
                if (parsedGeometry.matricesWeightsExtra) {
                    mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
                }
                mesh.setIndices(parsedGeometry.indices, null);
            }
            // SubMeshes
            if (parsedGeometry.subMeshes) {
                mesh.subMeshes = [];
                for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
                    var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
                    BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
                }
            }
            // Flat shading
            if (mesh._shouldGenerateFlatShading) {
                mesh.convertToFlatShadedMesh();
                delete mesh._shouldGenerateFlatShading;
            }
            // Update
            mesh.computeWorldMatrix(true);
            scene.onMeshImportedObservable.notifyObservers(mesh);
        };
        Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
            var epsilon = 1e-3;
            if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
                return;
            }
            var noInfluenceBoneIndex = 0.0;
            if (parsedGeometry.skeletonId > -1) {
                var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
                if (!skeleton) {
                    return;
                }
                noInfluenceBoneIndex = skeleton.bones.length;
            }
            else {
                return;
            }
            var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
            var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
            var matricesWeights = parsedGeometry.matricesWeights;
            var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
            var influencers = parsedGeometry.numBoneInfluencer;
            var size = matricesWeights.length;
            for (var i = 0; i < size; i += 4) {
                var weight = 0.0;
                var firstZeroWeight = -1;
                for (var j = 0; j < 4; j++) {
                    var w = matricesWeights[i + j];
                    weight += w;
                    if (w < epsilon && firstZeroWeight < 0) {
                        firstZeroWeight = j;
                    }
                }
                if (matricesWeightsExtra) {
                    for (var j = 0; j < 4; j++) {
                        var w = matricesWeightsExtra[i + j];
                        weight += w;
                        if (w < epsilon && firstZeroWeight < 0) {
                            firstZeroWeight = j + 4;
                        }
                    }
                }
                if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
                    firstZeroWeight = influencers - 1;
                }
                if (weight > epsilon) {
                    var mweight = 1.0 / weight;
                    for (var j = 0; j < 4; j++) {
                        matricesWeights[i + j] *= mweight;
                    }
                    if (matricesWeightsExtra) {
                        for (var j = 0; j < 4; j++) {
                            matricesWeightsExtra[i + j] *= mweight;
                        }
                    }
                }
                else {
                    if (firstZeroWeight >= 4) {
                        matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
                        matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
                    }
                    else {
                        matricesWeights[i + firstZeroWeight] = 1.0 - weight;
                        matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
                    }
                }
            }
            mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
            if (parsedGeometry.matricesWeightsExtra) {
                mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
            }
        };
        /**
         * Create a new geometry from persisted data (Using .babylon file format)
         * @param parsedVertexData defines the persisted data
         * @param scene defines the hosting scene
         * @param rootUrl defines the root url to use to load assets (like delayed data)
         * @returns the new geometry object
         */
        Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
            if (scene.getGeometryByID(parsedVertexData.id)) {
                return null; // null since geometry could be something else than a box...
            }
            var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
            }
            if (parsedVertexData.delayLoadingFile) {
                geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
                geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
                geometry._delayInfo = [];
                if (parsedVertexData.hasUVs) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
                }
                if (parsedVertexData.hasUVs2) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (parsedVertexData.hasUVs3) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
                }
                if (parsedVertexData.hasUVs4) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
                }
                if (parsedVertexData.hasUVs5) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
                }
                if (parsedVertexData.hasUVs6) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
                }
                if (parsedVertexData.hasColors) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
                }
                if (parsedVertexData.hasMatricesIndices) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                }
                if (parsedVertexData.hasMatricesWeights) {
                    geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                }
                geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
            }
            else {
                BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
            }
            scene.pushGeometry(geometry, true);
            return geometry;
        };
        return Geometry;
    }());
    BABYLON.Geometry = Geometry;
    // Primitives
    /// Abstract class
    /**
     * Abstract class used to provide common services for all typed geometries
     * @hidden
     */
    var _PrimitiveGeometry = /** @class */ (function (_super) {
        __extends(_PrimitiveGeometry, _super);
        /**
         * Creates a new typed geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         */
        function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
            if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
            if (mesh === void 0) { mesh = null; }
            var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
            _this._canBeRegenerated = _canBeRegenerated;
            _this._beingRegenerated = true;
            _this.regenerate();
            _this._beingRegenerated = false;
            return _this;
        }
        /**
         * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
         * @returns true if the geometry can be regenerated
         */
        _PrimitiveGeometry.prototype.canBeRegenerated = function () {
            return this._canBeRegenerated;
        };
        /**
         * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
         */
        _PrimitiveGeometry.prototype.regenerate = function () {
            if (!this._canBeRegenerated) {
                return;
            }
            this._beingRegenerated = true;
            this.setAllVerticesData(this._regenerateVertexData(), false);
            this._beingRegenerated = false;
        };
        /**
         * Clone the geometry
         * @param id defines the unique ID of the new geometry
         * @returns the new geometry
         */
        _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
            return _super.prototype.copy.call(this, id);
        };
        // overrides
        _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
            if (!this._beingRegenerated) {
                return;
            }
            _super.prototype.setAllVerticesData.call(this, vertexData, false);
        };
        _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
            if (!this._beingRegenerated) {
                return;
            }
            _super.prototype.setVerticesData.call(this, kind, data, false);
        };
        // to override
        /** @hidden */
        _PrimitiveGeometry.prototype._regenerateVertexData = function () {
            throw new Error("Abstract method");
        };
        _PrimitiveGeometry.prototype.copy = function (id) {
            throw new Error("Must be overriden in sub-classes.");
        };
        _PrimitiveGeometry.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.canBeRegenerated = this.canBeRegenerated();
            return serializationObject;
        };
        return _PrimitiveGeometry;
    }(Geometry));
    BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
    /**
     * Creates a ribbon geometry
     * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
     */
    var RibbonGeometry = /** @class */ (function (_super) {
        __extends(RibbonGeometry, _super);
        /**
         * Creates a ribbon geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param pathArray defines the array of paths to use
         * @param closeArray defines if the last path and the first path must be  joined
         * @param closePath defines if the last and first points of each path in your pathArray must be joined
         * @param offset defines the offset between points
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function RibbonGeometry(id, scene, 
        /**
         * Defines the array of paths to use
         */
        pathArray, 
        /**
         * Defines if the last and first points of each path in your pathArray must be joined
         */
        closeArray, 
        /**
         * Defines if the last and first points of each path in your pathArray must be joined
         */
        closePath, 
        /**
         * Defines the offset between points
         */
        offset, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.pathArray = pathArray;
            _this.closeArray = closeArray;
            _this.closePath = closePath;
            _this.offset = offset;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        RibbonGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
        };
        RibbonGeometry.prototype.copy = function (id) {
            return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
        };
        return RibbonGeometry;
    }(_PrimitiveGeometry));
    BABYLON.RibbonGeometry = RibbonGeometry;
    /**
     * Creates a box geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#box
     */
    var BoxGeometry = /** @class */ (function (_super) {
        __extends(BoxGeometry, _super);
        /**
         * Creates a box geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param size defines the zise of the box (width, height and depth are the same)
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function BoxGeometry(id, scene, 
        /**
         * Defines the zise of the box (width, height and depth are the same)
         */
        size, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.size = size;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        BoxGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
        };
        BoxGeometry.prototype.copy = function (id) {
            return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
        };
        BoxGeometry.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.size = this.size;
            return serializationObject;
        };
        BoxGeometry.Parse = function (parsedBox, scene) {
            if (scene.getGeometryByID(parsedBox.id)) {
                return null; // null since geometry could be something else than a box...
            }
            var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
            }
            scene.pushGeometry(box, true);
            return box;
        };
        return BoxGeometry;
    }(_PrimitiveGeometry));
    BABYLON.BoxGeometry = BoxGeometry;
    /**
     * Creates a sphere geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
     */
    var SphereGeometry = /** @class */ (function (_super) {
        __extends(SphereGeometry, _super);
        /**
         * Create a new sphere geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param segments defines the number of segments to use to create the sphere
         * @param diameter defines the diameter of the sphere
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function SphereGeometry(id, scene, 
        /**
         * Defines the number of segments to use to create the sphere
         */
        segments, 
        /**
         * Defines the diameter of the sphere
         */
        diameter, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.segments = segments;
            _this.diameter = diameter;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        SphereGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
        };
        SphereGeometry.prototype.copy = function (id) {
            return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
        };
        SphereGeometry.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.segments = this.segments;
            serializationObject.diameter = this.diameter;
            return serializationObject;
        };
        SphereGeometry.Parse = function (parsedSphere, scene) {
            if (scene.getGeometryByID(parsedSphere.id)) {
                return null; // null since geometry could be something else than a sphere...
            }
            var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
            }
            scene.pushGeometry(sphere, true);
            return sphere;
        };
        return SphereGeometry;
    }(_PrimitiveGeometry));
    BABYLON.SphereGeometry = SphereGeometry;
    /**
     * Creates a disc geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
     */
    var DiscGeometry = /** @class */ (function (_super) {
        __extends(DiscGeometry, _super);
        /**
         * Creates a new disc geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param radius defines the radius of the disc
         * @param tessellation defines the tesselation factor to apply to the disc
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function DiscGeometry(id, scene, 
        /**
         * Defines the radius of the disc
         */
        radius, 
        /**
         * Defines the tesselation factor to apply to the disc
         */
        tessellation, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.radius = radius;
            _this.tessellation = tessellation;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        DiscGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
        };
        DiscGeometry.prototype.copy = function (id) {
            return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
        };
        return DiscGeometry;
    }(_PrimitiveGeometry));
    BABYLON.DiscGeometry = DiscGeometry;
    /**
     * Creates a new cylinder geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
     */
    var CylinderGeometry = /** @class */ (function (_super) {
        __extends(CylinderGeometry, _super);
        /**
         * Creates a new cylinder geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param height defines the height of the cylinder
         * @param diameterTop defines the diameter of the cylinder's top cap
         * @param diameterBottom defines the diameter of the cylinder's bottom cap
         * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
         * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function CylinderGeometry(id, scene, 
        /**
         * Defines the height of the cylinder
         */
        height, 
        /**
         * Defines the diameter of the cylinder's top cap
         */
        diameterTop, 
        /**
         * Defines the diameter of the cylinder's bottom cap
         */
        diameterBottom, 
        /**
         * Defines the tessellation factor to apply to the cylinder
         */
        tessellation, 
        /**
         * Defines the number of subdivisions to apply to the cylinder (1 by default)
         */
        subdivisions, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (subdivisions === void 0) { subdivisions = 1; }
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.height = height;
            _this.diameterTop = diameterTop;
            _this.diameterBottom = diameterBottom;
            _this.tessellation = tessellation;
            _this.subdivisions = subdivisions;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        CylinderGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
        };
        CylinderGeometry.prototype.copy = function (id) {
            return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
        };
        CylinderGeometry.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;
        };
        CylinderGeometry.Parse = function (parsedCylinder, scene) {
            if (scene.getGeometryByID(parsedCylinder.id)) {
                return null; // null since geometry could be something else than a cylinder...
            }
            var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
            }
            scene.pushGeometry(cylinder, true);
            return cylinder;
        };
        return CylinderGeometry;
    }(_PrimitiveGeometry));
    BABYLON.CylinderGeometry = CylinderGeometry;
    /**
     * Creates a new torus geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
     */
    var TorusGeometry = /** @class */ (function (_super) {
        __extends(TorusGeometry, _super);
        /**
         * Creates a new torus geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param diameter defines the diameter of the torus
         * @param thickness defines the thickness of the torus (ie. internal diameter)
         * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function TorusGeometry(id, scene, 
        /**
         * Defines the diameter of the torus
         */
        diameter, 
        /**
         * Defines the thickness of the torus (ie. internal diameter)
         */
        thickness, 
        /**
         * Defines the tesselation factor to apply to the torus
         */
        tessellation, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.diameter = diameter;
            _this.thickness = thickness;
            _this.tessellation = tessellation;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        TorusGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
        };
        TorusGeometry.prototype.copy = function (id) {
            return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
        };
        TorusGeometry.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.diameter = this.diameter;
            serializationObject.thickness = this.thickness;
            serializationObject.tessellation = this.tessellation;
            return serializationObject;
        };
        TorusGeometry.Parse = function (parsedTorus, scene) {
            if (scene.getGeometryByID(parsedTorus.id)) {
                return null; // null since geometry could be something else than a torus...
            }
            var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
            }
            scene.pushGeometry(torus, true);
            return torus;
        };
        return TorusGeometry;
    }(_PrimitiveGeometry));
    BABYLON.TorusGeometry = TorusGeometry;
    /**
     * Creates a new ground geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
     */
    var GroundGeometry = /** @class */ (function (_super) {
        __extends(GroundGeometry, _super);
        /**
         * Creates a new ground geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param width defines the width of the ground
         * @param height defines the height of the ground
         * @param subdivisions defines the subdivisions to apply to the ground
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         */
        function GroundGeometry(id, scene, 
        /**
         * Defines the width of the ground
         */
        width, 
        /**
         * Defines the height of the ground
         */
        height, 
        /**
         * Defines the subdivisions to apply to the ground
         */
        subdivisions, canBeRegenerated, mesh) {
            if (mesh === void 0) { mesh = null; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.width = width;
            _this.height = height;
            _this.subdivisions = subdivisions;
            return _this;
        }
        /** @hidden */
        GroundGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
        };
        GroundGeometry.prototype.copy = function (id) {
            return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
        };
        GroundGeometry.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.width = this.width;
            serializationObject.height = this.height;
            serializationObject.subdivisions = this.subdivisions;
            return serializationObject;
        };
        GroundGeometry.Parse = function (parsedGround, scene) {
            if (scene.getGeometryByID(parsedGround.id)) {
                return null; // null since geometry could be something else than a ground...
            }
            var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
            }
            scene.pushGeometry(ground, true);
            return ground;
        };
        return GroundGeometry;
    }(_PrimitiveGeometry));
    BABYLON.GroundGeometry = GroundGeometry;
    /**
     * Creates a tiled ground geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
     */
    var TiledGroundGeometry = /** @class */ (function (_super) {
        __extends(TiledGroundGeometry, _super);
        /**
         * Creates a tiled ground geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param xmin defines the minimum value on X axis
         * @param zmin defines the minimum value on Z axis
         * @param xmax defines the maximum value on X axis
         * @param zmax defines the maximum value on Z axis
         * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
         * @param precision defines the precision to use when computing the tiles
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         */
        function TiledGroundGeometry(id, scene, 
        /**
         * Defines the minimum value on X axis
         */
        xmin, 
        /**
         * Defines the minimum value on Z axis
         */
        zmin, 
        /**
         * Defines the maximum value on X axis
         */
        xmax, 
        /**
         * Defines the maximum value on Z axis
         */
        zmax, 
        /**
         * Defines the subdivisions to apply to the ground
         */
        subdivisions, 
        /**
         * Defines the precision to use when computing the tiles
         */
        precision, canBeRegenerated, mesh) {
            if (mesh === void 0) { mesh = null; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.xmin = xmin;
            _this.zmin = zmin;
            _this.xmax = xmax;
            _this.zmax = zmax;
            _this.subdivisions = subdivisions;
            _this.precision = precision;
            return _this;
        }
        /** @hidden */
        TiledGroundGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
        };
        TiledGroundGeometry.prototype.copy = function (id) {
            return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
        };
        return TiledGroundGeometry;
    }(_PrimitiveGeometry));
    BABYLON.TiledGroundGeometry = TiledGroundGeometry;
    /**
     * Creates a plane geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
     */
    var PlaneGeometry = /** @class */ (function (_super) {
        __extends(PlaneGeometry, _super);
        /**
         * Creates a plane geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param size defines the size of the plane (width === height)
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function PlaneGeometry(id, scene, 
        /**
         * Defines the size of the plane (width === height)
         */
        size, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.size = size;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        PlaneGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
        };
        PlaneGeometry.prototype.copy = function (id) {
            return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
        };
        PlaneGeometry.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.size = this.size;
            return serializationObject;
        };
        PlaneGeometry.Parse = function (parsedPlane, scene) {
            if (scene.getGeometryByID(parsedPlane.id)) {
                return null; // null since geometry could be something else than a ground...
            }
            var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
            }
            scene.pushGeometry(plane, true);
            return plane;
        };
        return PlaneGeometry;
    }(_PrimitiveGeometry));
    BABYLON.PlaneGeometry = PlaneGeometry;
    /**
     * Creates a torus knot geometry
     * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
     */
    var TorusKnotGeometry = /** @class */ (function (_super) {
        __extends(TorusKnotGeometry, _super);
        /**
         * Creates a torus knot geometry
         * @param id defines the unique ID of the geometry
         * @param scene defines the hosting scene
         * @param radius defines the radius of the torus knot
         * @param tube defines the thickness of the torus knot tube
         * @param radialSegments defines the number of radial segments
         * @param tubularSegments defines the number of tubular segments
         * @param p defines the first number of windings
         * @param q defines the second number of windings
         * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
         * @param mesh defines the hosting mesh (can be null)
         * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        function TorusKnotGeometry(id, scene, 
        /**
         * Defines the radius of the torus knot
         */
        radius, 
        /**
         * Defines the thickness of the torus knot tube
         */
        tube, 
        /**
         * Defines the number of radial segments
         */
        radialSegments, 
        /**
         * Defines the number of tubular segments
         */
        tubularSegments, 
        /**
         * Defines the first number of windings
         */
        p, 
        /**
         * Defines the second number of windings
         */
        q, canBeRegenerated, mesh, 
        /**
         * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
         */
        side) {
            if (mesh === void 0) { mesh = null; }
            if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
            var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
            _this.radius = radius;
            _this.tube = tube;
            _this.radialSegments = radialSegments;
            _this.tubularSegments = tubularSegments;
            _this.p = p;
            _this.q = q;
            _this.side = side;
            return _this;
        }
        /** @hidden */
        TorusKnotGeometry.prototype._regenerateVertexData = function () {
            return BABYLON.VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
        };
        TorusKnotGeometry.prototype.copy = function (id) {
            return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
        };
        TorusKnotGeometry.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;
        };
        TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
            if (scene.getGeometryByID(parsedTorusKnot.id)) {
                return null; // null since geometry could be something else than a ground...
            }
            var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
            if (BABYLON.Tags) {
                BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
            }
            scene.pushGeometry(torusKnot, true);
            return torusKnot;
        };
        return TorusKnotGeometry;
    }(_PrimitiveGeometry));
    BABYLON.TorusKnotGeometry = TorusKnotGeometry;
    //}
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.geometry.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
     */
    var PerformanceMonitor = /** @class */ (function () {
        /**
         * constructor
         * @param frameSampleSize The number of samples required to saturate the sliding window
         */
        function PerformanceMonitor(frameSampleSize) {
            if (frameSampleSize === void 0) { frameSampleSize = 30; }
            this._enabled = true;
            this._rollingFrameTime = new RollingAverage(frameSampleSize);
        }
        /**
         * Samples current frame
         * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
         */
        PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
            if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
            if (!this._enabled) {
                return;
            }
            if (this._lastFrameTimeMs != null) {
                var dt = timeMs - this._lastFrameTimeMs;
                this._rollingFrameTime.add(dt);
            }
            this._lastFrameTimeMs = timeMs;
        };
        Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
            /**
             * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
             */
            get: function () {
                return this._rollingFrameTime.average;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
            /**
             * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
             */
            get: function () {
                return this._rollingFrameTime.variance;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
            /**
             * Returns the frame time of the most recent frame
             */
            get: function () {
                return this._rollingFrameTime.history(0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
            /**
             * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
             */
            get: function () {
                return 1000.0 / this._rollingFrameTime.average;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
            /**
             * Returns the average framerate in frames per second using the most recent frame time
             */
            get: function () {
                var history = this._rollingFrameTime.history(0);
                if (history === 0) {
                    return 0;
                }
                return 1000.0 / history;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
            /**
             * Returns true if enough samples have been taken to completely fill the sliding window
             */
            get: function () {
                return this._rollingFrameTime.isSaturated();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Enables contributions to the sliding window sample set
         */
        PerformanceMonitor.prototype.enable = function () {
            this._enabled = true;
        };
        /**
         * Disables contributions to the sliding window sample set
         * Samples will not be interpolated over the disabled period
         */
        PerformanceMonitor.prototype.disable = function () {
            this._enabled = false;
            //clear last sample to avoid interpolating over the disabled period when next enabled
            this._lastFrameTimeMs = null;
        };
        Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
            /**
             * Returns true if sampling is enabled
             */
            get: function () {
                return this._enabled;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Resets performance monitor
         */
        PerformanceMonitor.prototype.reset = function () {
            //clear last sample to avoid interpolating over the disabled period when next enabled
            this._lastFrameTimeMs = null;
            //wipe record
            this._rollingFrameTime.reset();
        };
        return PerformanceMonitor;
    }());
    BABYLON.PerformanceMonitor = PerformanceMonitor;
    /**
     * RollingAverage
     *
     * Utility to efficiently compute the rolling average and variance over a sliding window of samples
     */
    var RollingAverage = /** @class */ (function () {
        /**
         * constructor
         * @param length The number of samples required to saturate the sliding window
         */
        function RollingAverage(length) {
            this._samples = new Array(length);
            this.reset();
        }
        /**
         * Adds a sample to the sample set
         * @param v The sample value
         */
        RollingAverage.prototype.add = function (v) {
            //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
            var delta;
            //we need to check if we've already wrapped round
            if (this.isSaturated()) {
                //remove bottom of stack from mean
                var bottomValue = this._samples[this._pos];
                delta = bottomValue - this.average;
                this.average -= delta / (this._sampleCount - 1);
                this._m2 -= delta * (bottomValue - this.average);
            }
            else {
                this._sampleCount++;
            }
            //add new value to mean
            delta = v - this.average;
            this.average += delta / (this._sampleCount);
            this._m2 += delta * (v - this.average);
            //set the new variance
            this.variance = this._m2 / (this._sampleCount - 1);
            this._samples[this._pos] = v;
            this._pos++;
            this._pos %= this._samples.length; //positive wrap around
        };
        /**
         * Returns previously added values or null if outside of history or outside the sliding window domain
         * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
         * @return Value previously recorded with add() or null if outside of range
         */
        RollingAverage.prototype.history = function (i) {
            if ((i >= this._sampleCount) || (i >= this._samples.length)) {
                return 0;
            }
            var i0 = this._wrapPosition(this._pos - 1.0);
            return this._samples[this._wrapPosition(i0 - i)];
        };
        /**
         * Returns true if enough samples have been taken to completely fill the sliding window
         * @return true if sample-set saturated
         */
        RollingAverage.prototype.isSaturated = function () {
            return this._sampleCount >= this._samples.length;
        };
        /**
         * Resets the rolling average (equivalent to 0 samples taken so far)
         */
        RollingAverage.prototype.reset = function () {
            this.average = 0;
            this.variance = 0;
            this._sampleCount = 0;
            this._pos = 0;
            this._m2 = 0;
        };
        /**
         * Wraps a value around the sample range boundaries
         * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
         * @return Wrapped position in sample range
         */
        RollingAverage.prototype._wrapPosition = function (i) {
            var max = this._samples.length;
            return ((i % max) + max) % max;
        };
        return RollingAverage;
    }());
    BABYLON.RollingAverage = RollingAverage;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.performanceMonitor.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * "Static Class" containing the most commonly used helper while dealing with material for
     * rendering purpose.
     *
     * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
     *
     * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
     */
    var MaterialHelper = /** @class */ (function () {
        function MaterialHelper() {
        }
        /**
         * Bind the current view position to an effect.
         * @param effect The effect to be bound
         * @param scene The scene the eyes position is used from
         */
        MaterialHelper.BindEyePosition = function (effect, scene) {
            if (scene._forcedViewPosition) {
                effect.setVector3("vEyePosition", scene._forcedViewPosition);
                return;
            }
            effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
        };
        /**
         * Helps preparing the defines values about the UVs in used in the effect.
         * UVs are shared as much as we can accross channels in the shaders.
         * @param texture The texture we are preparing the UVs for
         * @param defines The defines to update
         * @param key The channel key "diffuse", "specular"... used in the shader
         */
        MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
            defines._needUVs = true;
            defines[key] = true;
            if (texture.getTextureMatrix().isIdentity(true)) {
                defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
                if (texture.coordinatesIndex === 0) {
                    defines["MAINUV1"] = true;
                }
                else {
                    defines["MAINUV2"] = true;
                }
            }
            else {
                defines[key + "DIRECTUV"] = 0;
            }
        };
        /**
         * Binds a texture matrix value to its corrsponding uniform
         * @param texture The texture to bind the matrix for
         * @param uniformBuffer The uniform buffer receivin the data
         * @param key The channel key "diffuse", "specular"... used in the shader
         */
        MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
            var matrix = texture.getTextureMatrix();
            if (!matrix.isIdentity(true)) {
                uniformBuffer.updateMatrix(key + "Matrix", matrix);
            }
        };
        /**
         * Helper used to prepare the list of defines associated with misc. values for shader compilation
         * @param mesh defines the current mesh
         * @param scene defines the current scene
         * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
         * @param pointsCloud defines if point cloud rendering has to be turned on
         * @param fogEnabled defines if fog has to be turned on
         * @param alphaTest defines if alpha testing has to be turned on
         * @param defines defines the current list of defines
         */
        MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
            if (defines._areMiscDirty) {
                defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
                defines["POINTSIZE"] = pointsCloud;
                defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
                defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
                defines["ALPHATEST"] = alphaTest;
            }
        };
        /**
         * Helper used to prepare the list of defines associated with frame values for shader compilation
         * @param scene defines the current scene
         * @param engine defines the current engine
         * @param defines specifies the list of active defines
         * @param useInstances defines if instances have to be turned on
         * @param useClipPlane defines if clip plane have to be turned on
         */
        MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
            if (useClipPlane === void 0) { useClipPlane = null; }
            var changed = false;
            var useClipPlane1 = false;
            var useClipPlane2 = false;
            var useClipPlane3 = false;
            var useClipPlane4 = false;
            useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
            useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
            useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
            useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
            if (defines["CLIPPLANE"] !== useClipPlane1) {
                defines["CLIPPLANE"] = useClipPlane1;
                changed = true;
            }
            if (defines["CLIPPLANE2"] !== useClipPlane2) {
                defines["CLIPPLANE2"] = useClipPlane2;
                changed = true;
            }
            if (defines["CLIPPLANE3"] !== useClipPlane3) {
                defines["CLIPPLANE3"] = useClipPlane3;
                changed = true;
            }
            if (defines["CLIPPLANE4"] !== useClipPlane4) {
                defines["CLIPPLANE4"] = useClipPlane4;
                changed = true;
            }
            if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
                defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
                changed = true;
            }
            if (defines["INSTANCES"] !== useInstances) {
                defines["INSTANCES"] = useInstances;
                changed = true;
            }
            if (changed) {
                defines.markAsUnprocessed();
            }
        };
        /**
         * Prepares the defines used in the shader depending on the attributes data available in the mesh
         * @param mesh The mesh containing the geometry data we will draw
         * @param defines The defines to update
         * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
         * @param useBones Precise whether bones should be used or not (override mesh info)
         * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
         * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
         * @returns false if defines are considered not dirty and have not been checked
         */
        MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
            if (useMorphTargets === void 0) { useMorphTargets = false; }
            if (useVertexAlpha === void 0) { useVertexAlpha = true; }
            if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
                return false;
            }
            defines._normals = defines._needNormals;
            defines._uvs = defines._needUVs;
            defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
            if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
                defines["TANGENT"] = true;
            }
            if (defines._needUVs) {
                defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
                defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
            }
            else {
                defines["UV1"] = false;
                defines["UV2"] = false;
            }
            if (useVertexColor) {
                var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
                defines["VERTEXCOLOR"] = hasVertexColors;
                defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
            }
            if (useBones) {
                if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                    defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
                    defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
                }
                else {
                    defines["NUM_BONE_INFLUENCERS"] = 0;
                    defines["BonesPerMesh"] = 0;
                }
            }
            if (useMorphTargets) {
                var manager = mesh.morphTargetManager;
                if (manager) {
                    defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
                    defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
                    defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
                    defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
                }
                else {
                    defines["MORPHTARGETS_TANGENT"] = false;
                    defines["MORPHTARGETS_NORMAL"] = false;
                    defines["MORPHTARGETS"] = false;
                    defines["NUM_MORPH_INFLUENCERS"] = 0;
                }
            }
            return true;
        };
        /**
         * Prepares the defines related to the light information passed in parameter
         * @param scene The scene we are intending to draw
         * @param mesh The mesh the effect is compiling for
         * @param defines The defines to update
         * @param specularSupported Specifies whether specular is supported or not (override lights data)
         * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
         * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
         * @returns true if normals will be required for the rest of the effect
         */
        MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            if (disableLighting === void 0) { disableLighting = false; }
            if (!defines._areLightsDirty) {
                return defines._needNormals;
            }
            var lightIndex = 0;
            var needNormals = false;
            var needRebuild = false;
            var lightmapMode = false;
            var shadowEnabled = false;
            var specularEnabled = false;
            if (scene.lightsEnabled && !disableLighting) {
                for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
                    var light = _a[_i];
                    needNormals = true;
                    if (defines["LIGHT" + lightIndex] === undefined) {
                        needRebuild = true;
                    }
                    defines["LIGHT" + lightIndex] = true;
                    defines["SPOTLIGHT" + lightIndex] = false;
                    defines["HEMILIGHT" + lightIndex] = false;
                    defines["POINTLIGHT" + lightIndex] = false;
                    defines["DIRLIGHT" + lightIndex] = false;
                    light.prepareLightSpecificDefines(defines, lightIndex);
                    // FallOff.
                    defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
                    defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
                    defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
                    switch (light.falloffType) {
                        case BABYLON.Light.FALLOFF_GLTF:
                            defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
                            break;
                        case BABYLON.Light.FALLOFF_PHYSICAL:
                            defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
                            break;
                        case BABYLON.Light.FALLOFF_STANDARD:
                            defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
                            break;
                    }
                    // Specular
                    if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
                        specularEnabled = true;
                    }
                    // Shadows
                    defines["SHADOW" + lightIndex] = false;
                    defines["SHADOWPCF" + lightIndex] = false;
                    defines["SHADOWPCSS" + lightIndex] = false;
                    defines["SHADOWPOISSON" + lightIndex] = false;
                    defines["SHADOWESM" + lightIndex] = false;
                    defines["SHADOWCUBE" + lightIndex] = false;
                    defines["SHADOWLOWQUALITY" + lightIndex] = false;
                    defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
                    if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
                        var shadowGenerator = light.getShadowGenerator();
                        if (shadowGenerator) {
                            var shadowMap = shadowGenerator.getShadowMap();
                            if (shadowMap) {
                                if (shadowMap.renderList && shadowMap.renderList.length > 0) {
                                    shadowEnabled = true;
                                    shadowGenerator.prepareDefines(defines, lightIndex);
                                }
                            }
                        }
                    }
                    if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
                        lightmapMode = true;
                        defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
                        defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
                    }
                    else {
                        defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
                        defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
                    }
                    lightIndex++;
                    if (lightIndex === maxSimultaneousLights) {
                        break;
                    }
                }
            }
            defines["SPECULARTERM"] = specularEnabled;
            defines["SHADOWS"] = shadowEnabled;
            // Resetting all other lights if any
            for (var index = lightIndex; index < maxSimultaneousLights; index++) {
                if (defines["LIGHT" + index] !== undefined) {
                    defines["LIGHT" + index] = false;
                    defines["HEMILIGHT" + lightIndex] = false;
                    defines["POINTLIGHT" + lightIndex] = false;
                    defines["DIRLIGHT" + lightIndex] = false;
                    defines["SPOTLIGHT" + lightIndex] = false;
                    defines["SHADOW" + lightIndex] = false;
                }
            }
            var caps = scene.getEngine().getCaps();
            if (defines["SHADOWFLOAT"] === undefined) {
                needRebuild = true;
            }
            defines["SHADOWFLOAT"] = shadowEnabled &&
                ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
                    (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
            defines["LIGHTMAPEXCLUDED"] = lightmapMode;
            if (needRebuild) {
                defines.rebuild();
            }
            return needNormals;
        };
        /**
         * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
         * that won t be acctive due to defines being turned off.
         * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
         * @param samplersList The samplers list
         * @param defines The defines helping in the list generation
         * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
         */
        MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            var uniformsList;
            var uniformBuffersList = null;
            if (uniformsListOrOptions.uniformsNames) {
                var options = uniformsListOrOptions;
                uniformsList = options.uniformsNames;
                uniformBuffersList = options.uniformBuffersNames;
                samplersList = options.samplers;
                defines = options.defines;
                maxSimultaneousLights = options.maxSimultaneousLights;
            }
            else {
                uniformsList = uniformsListOrOptions;
                if (!samplersList) {
                    samplersList = [];
                }
            }
            for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
                if (!defines["LIGHT" + lightIndex]) {
                    break;
                }
                uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
                if (uniformBuffersList) {
                    uniformBuffersList.push("Light" + lightIndex);
                }
                samplersList.push("shadowSampler" + lightIndex);
                samplersList.push("depthSampler" + lightIndex);
                if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
                    samplersList.push("projectionLightSampler" + lightIndex);
                    uniformsList.push("textureProjectionMatrix" + lightIndex);
                }
            }
            if (defines["NUM_MORPH_INFLUENCERS"]) {
                uniformsList.push("morphTargetInfluences");
            }
        };
        /**
         * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
         * @param defines The defines to update while falling back
         * @param fallbacks The authorized effect fallbacks
         * @param maxSimultaneousLights The maximum number of lights allowed
         * @param rank the current rank of the Effect
         * @returns The newly affected rank
         */
        MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            if (rank === void 0) { rank = 0; }
            var lightFallbackRank = 0;
            for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
                if (!defines["LIGHT" + lightIndex]) {
                    break;
                }
                if (lightIndex > 0) {
                    lightFallbackRank = rank + lightIndex;
                    fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
                }
                if (!defines["SHADOWS"]) {
                    if (defines["SHADOW" + lightIndex]) {
                        fallbacks.addFallback(rank, "SHADOW" + lightIndex);
                    }
                    if (defines["SHADOWPCF" + lightIndex]) {
                        fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
                    }
                    if (defines["SHADOWPCSS" + lightIndex]) {
                        fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
                    }
                    if (defines["SHADOWPOISSON" + lightIndex]) {
                        fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
                    }
                    if (defines["SHADOWESM" + lightIndex]) {
                        fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
                    }
                }
            }
            return lightFallbackRank++;
        };
        /**
         * Prepares the list of attributes required for morph targets according to the effect defines.
         * @param attribs The current list of supported attribs
         * @param mesh The mesh to prepare the morph targets attributes for
         * @param defines The current Defines of the effect
         */
        MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
            var influencers = defines["NUM_MORPH_INFLUENCERS"];
            if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
                var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
                var manager = mesh.morphTargetManager;
                var normal = manager && manager.supportsNormals && defines["NORMAL"];
                var tangent = manager && manager.supportsTangents && defines["TANGENT"];
                for (var index = 0; index < influencers; index++) {
                    attribs.push(BABYLON.VertexBuffer.PositionKind + index);
                    if (normal) {
                        attribs.push(BABYLON.VertexBuffer.NormalKind + index);
                    }
                    if (tangent) {
                        attribs.push(BABYLON.VertexBuffer.TangentKind + index);
                    }
                    if (attribs.length > maxAttributesCount) {
                        BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
                    }
                }
            }
        };
        /**
         * Prepares the list of attributes required for bones according to the effect defines.
         * @param attribs The current list of supported attribs
         * @param mesh The mesh to prepare the bones attributes for
         * @param defines The current Defines of the effect
         * @param fallbacks The current efffect fallback strategy
         */
        MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
            if (defines["NUM_BONE_INFLUENCERS"] > 0) {
                fallbacks.addCPUSkinningFallback(0, mesh);
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (defines["NUM_BONE_INFLUENCERS"] > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
            }
        };
        /**
         * Prepares the list of attributes required for instances according to the effect defines.
         * @param attribs The current list of supported attribs
         * @param defines The current Defines of the effect
         */
        MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
            if (defines["INSTANCES"]) {
                attribs.push("world0");
                attribs.push("world1");
                attribs.push("world2");
                attribs.push("world3");
            }
        };
        /**
         * Binds the light shadow information to the effect for the given mesh.
         * @param light The light containing the generator
         * @param scene The scene the lights belongs to
         * @param mesh The mesh we are binding the information to render
         * @param lightIndex The light index in the effect used to render the mesh
         * @param effect The effect we are binding the data to
         */
        MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
            if (light.shadowEnabled && mesh.receiveShadows) {
                var shadowGenerator = light.getShadowGenerator();
                if (shadowGenerator) {
                    shadowGenerator.bindShadowLight(lightIndex, effect);
                }
            }
        };
        /**
         * Binds the light information to the effect.
         * @param light The light containing the generator
         * @param effect The effect we are binding the data to
         * @param lightIndex The light index in the effect used to render
         */
        MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
            light.transferToEffect(effect, lightIndex + "");
        };
        /**
         * Binds the lights information from the scene to the effect for the given mesh.
         * @param scene The scene the lights belongs to
         * @param mesh The mesh we are binding the information to render
         * @param effect The effect we are binding the data to
         * @param defines The generated defines for the effect
         * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
         * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
         */
        MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
            if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
            if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
            var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
            for (var i = 0; i < len; i++) {
                var light = mesh._lightSources[i];
                var iAsString = i.toString();
                var scaledIntensity = light.getScaledIntensity();
                light._uniformBuffer.bindToEffect(effect, "Light" + i);
                MaterialHelper.BindLightProperties(light, effect, i);
                light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
                light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
                if (defines["SPECULARTERM"]) {
                    light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
                    light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
                }
                // Shadows
                if (scene.shadowsEnabled) {
                    this.BindLightShadow(light, scene, mesh, iAsString, effect);
                }
                light._uniformBuffer.update();
            }
        };
        /**
         * Binds the fog information from the scene to the effect for the given mesh.
         * @param scene The scene the lights belongs to
         * @param mesh The mesh we are binding the information to render
         * @param effect The effect we are binding the data to
         * @param linearSpace Defines if the fog effect is applied in linear space
         */
        MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
            if (linearSpace === void 0) { linearSpace = false; }
            if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
                effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
                // Convert fog color to linear space if used in a linear space computed shader.
                if (linearSpace) {
                    scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
                    effect.setColor3("vFogColor", this._tempFogColor);
                }
                else {
                    effect.setColor3("vFogColor", scene.fogColor);
                }
            }
        };
        /**
         * Binds the bones information from the mesh to the effect.
         * @param mesh The mesh we are binding the information to render
         * @param effect The effect we are binding the data to
         */
        MaterialHelper.BindBonesParameters = function (mesh, effect) {
            if (!effect || !mesh) {
                return;
            }
            if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
                mesh.computeBonesUsingShaders = false;
            }
            if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                var matrices = mesh.skeleton.getTransformMatrices(mesh);
                if (matrices) {
                    effect.setMatrices("mBones", matrices);
                }
            }
        };
        /**
         * Binds the morph targets information from the mesh to the effect.
         * @param abstractMesh The mesh we are binding the information to render
         * @param effect The effect we are binding the data to
         */
        MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
            var manager = abstractMesh.morphTargetManager;
            if (!abstractMesh || !manager) {
                return;
            }
            effect.setFloatArray("morphTargetInfluences", manager.influences);
        };
        /**
         * Binds the logarithmic depth information from the scene to the effect for the given defines.
         * @param defines The generated defines used in the effect
         * @param effect The effect we are binding the data to
         * @param scene The scene we are willing to render with logarithmic scale for
         */
        MaterialHelper.BindLogDepth = function (defines, effect, scene) {
            if (defines["LOGARITHMICDEPTH"]) {
                effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
            }
        };
        /**
         * Binds the clip plane information from the scene to the effect.
         * @param scene The scene the clip plane information are extracted from
         * @param effect The effect we are binding the data to
         */
        MaterialHelper.BindClipPlane = function (effect, scene) {
            if (scene.clipPlane) {
                var clipPlane = scene.clipPlane;
                effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
            }
            if (scene.clipPlane2) {
                var clipPlane = scene.clipPlane2;
                effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
            }
            if (scene.clipPlane3) {
                var clipPlane = scene.clipPlane3;
                effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
            }
            if (scene.clipPlane4) {
                var clipPlane = scene.clipPlane4;
                effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
            }
        };
        MaterialHelper._tempFogColor = BABYLON.Color3.Black();
        return MaterialHelper;
    }());
    BABYLON.MaterialHelper = MaterialHelper;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.materialHelper.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Base class of materials working in push mode in babylon JS
     * @hidden
     */
    var PushMaterial = /** @class */ (function (_super) {
        __extends(PushMaterial, _super);
        function PushMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._normalMatrix = new BABYLON.Matrix();
            _this.storeEffectOnSubMeshes = true;
            return _this;
        }
        PushMaterial.prototype.getEffect = function () {
            return this._activeEffect;
        };
        PushMaterial.prototype.isReady = function (mesh, useInstances) {
            if (!mesh) {
                return false;
            }
            if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
                return true;
            }
            return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
        };
        /**
        * Binds the given world matrix to the active effect
        *
        * @param world the matrix to bind
        */
        PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
            this._activeEffect.setMatrix("world", world);
        };
        /**
         * Binds the given normal matrix to the active effect
         *
         * @param normalMatrix the matrix to bind
         */
        PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
            this._activeEffect.setMatrix("normalMatrix", normalMatrix);
        };
        PushMaterial.prototype.bind = function (world, mesh) {
            if (!mesh) {
                return;
            }
            this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
        };
        PushMaterial.prototype._afterBind = function (mesh, effect) {
            if (effect === void 0) { effect = null; }
            _super.prototype._afterBind.call(this, mesh);
            this.getScene()._cachedEffect = effect;
        };
        PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
            if (visibility === void 0) { visibility = 1; }
            return scene.isCachedMaterialInvalid(this, effect, visibility);
        };
        return PushMaterial;
    }(BABYLON.Material));
    BABYLON.PushMaterial = PushMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pushMaterial.js.map







var BABYLON;
(function (BABYLON) {
    /** @hidden */
    var StandardMaterialDefines = /** @class */ (function (_super) {
        __extends(StandardMaterialDefines, _super);
        function StandardMaterialDefines() {
            var _this = _super.call(this) || this;
            _this.MAINUV1 = false;
            _this.MAINUV2 = false;
            _this.DIFFUSE = false;
            _this.DIFFUSEDIRECTUV = 0;
            _this.AMBIENT = false;
            _this.AMBIENTDIRECTUV = 0;
            _this.OPACITY = false;
            _this.OPACITYDIRECTUV = 0;
            _this.OPACITYRGB = false;
            _this.REFLECTION = false;
            _this.EMISSIVE = false;
            _this.EMISSIVEDIRECTUV = 0;
            _this.SPECULAR = false;
            _this.SPECULARDIRECTUV = 0;
            _this.BUMP = false;
            _this.BUMPDIRECTUV = 0;
            _this.PARALLAX = false;
            _this.PARALLAXOCCLUSION = false;
            _this.SPECULAROVERALPHA = false;
            _this.CLIPPLANE = false;
            _this.CLIPPLANE2 = false;
            _this.CLIPPLANE3 = false;
            _this.CLIPPLANE4 = false;
            _this.ALPHATEST = false;
            _this.DEPTHPREPASS = false;
            _this.ALPHAFROMDIFFUSE = false;
            _this.POINTSIZE = false;
            _this.FOG = false;
            _this.SPECULARTERM = false;
            _this.DIFFUSEFRESNEL = false;
            _this.OPACITYFRESNEL = false;
            _this.REFLECTIONFRESNEL = false;
            _this.REFRACTIONFRESNEL = false;
            _this.EMISSIVEFRESNEL = false;
            _this.FRESNEL = false;
            _this.NORMAL = false;
            _this.UV1 = false;
            _this.UV2 = false;
            _this.VERTEXCOLOR = false;
            _this.VERTEXALPHA = false;
            _this.NUM_BONE_INFLUENCERS = 0;
            _this.BonesPerMesh = 0;
            _this.INSTANCES = false;
            _this.GLOSSINESS = false;
            _this.ROUGHNESS = false;
            _this.EMISSIVEASILLUMINATION = false;
            _this.LINKEMISSIVEWITHDIFFUSE = false;
            _this.REFLECTIONFRESNELFROMSPECULAR = false;
            _this.LIGHTMAP = false;
            _this.LIGHTMAPDIRECTUV = 0;
            _this.OBJECTSPACE_NORMALMAP = false;
            _this.USELIGHTMAPASSHADOWMAP = false;
            _this.REFLECTIONMAP_3D = false;
            _this.REFLECTIONMAP_SPHERICAL = false;
            _this.REFLECTIONMAP_PLANAR = false;
            _this.REFLECTIONMAP_CUBIC = false;
            _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
            _this.REFLECTIONMAP_PROJECTION = false;
            _this.REFLECTIONMAP_SKYBOX = false;
            _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
            _this.REFLECTIONMAP_EXPLICIT = false;
            _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
            _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
            _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
            _this.INVERTCUBICMAP = false;
            _this.LOGARITHMICDEPTH = false;
            _this.REFRACTION = false;
            _this.REFRACTIONMAP_3D = false;
            _this.REFLECTIONOVERALPHA = false;
            _this.TWOSIDEDLIGHTING = false;
            _this.SHADOWFLOAT = false;
            _this.MORPHTARGETS = false;
            _this.MORPHTARGETS_NORMAL = false;
            _this.MORPHTARGETS_TANGENT = false;
            _this.NUM_MORPH_INFLUENCERS = 0;
            _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
            _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
            _this.IMAGEPROCESSING = false;
            _this.VIGNETTE = false;
            _this.VIGNETTEBLENDMODEMULTIPLY = false;
            _this.VIGNETTEBLENDMODEOPAQUE = false;
            _this.TONEMAPPING = false;
            _this.TONEMAPPING_ACES = false;
            _this.CONTRAST = false;
            _this.COLORCURVES = false;
            _this.COLORGRADING = false;
            _this.COLORGRADING3D = false;
            _this.SAMPLER3DGREENDEPTH = false;
            _this.SAMPLER3DBGRMAP = false;
            _this.IMAGEPROCESSINGPOSTPROCESS = false;
            /**
             * If the reflection texture on this material is in linear color space
             * @hidden
             */
            _this.IS_REFLECTION_LINEAR = false;
            /**
             * If the refraction texture on this material is in linear color space
             * @hidden
             */
            _this.IS_REFRACTION_LINEAR = false;
            _this.EXPOSURE = false;
            _this.rebuild();
            return _this;
        }
        StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
            var modes = [
                "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
                "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
                "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
                "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
            ];
            for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
                var mode = modes_1[_i];
                this[mode] = (mode === modeToEnable);
            }
        };
        return StandardMaterialDefines;
    }(BABYLON.MaterialDefines));
    BABYLON.StandardMaterialDefines = StandardMaterialDefines;
    /**
     * This is the default material used in Babylon. It is the best trade off between quality
     * and performances.
     * @see http://doc.babylonjs.com/babylon101/materials
     */
    var StandardMaterial = /** @class */ (function (_super) {
        __extends(StandardMaterial, _super);
        /**
         * Instantiates a new standard material.
         * This is the default material used in Babylon. It is the best trade off between quality
         * and performances.
         * @see http://doc.babylonjs.com/babylon101/materials
         * @param name Define the name of the material in the scene
         * @param scene Define the scene the material belong to
         */
        function StandardMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * The color of the material lit by the environmental background lighting.
             * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
             */
            _this.ambientColor = new BABYLON.Color3(0, 0, 0);
            /**
             * The basic color of the material as viewed under a light.
             */
            _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
            /**
             * Define how the color and intensity of the highlight given by the light in the material.
             */
            _this.specularColor = new BABYLON.Color3(1, 1, 1);
            /**
             * Define the color of the material as if self lit.
             * This will be mixed in the final result even in the absence of light.
             */
            _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
            /**
             * Defines how sharp are the highlights in the material.
             * The bigger the value the sharper giving a more glossy feeling to the result.
             * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
             */
            _this.specularPower = 64;
            _this._useAlphaFromDiffuseTexture = false;
            _this._useEmissiveAsIllumination = false;
            _this._linkEmissiveWithDiffuse = false;
            _this._useSpecularOverAlpha = false;
            _this._useReflectionOverAlpha = false;
            _this._disableLighting = false;
            _this._useObjectSpaceNormalMap = false;
            _this._useParallax = false;
            _this._useParallaxOcclusion = false;
            /**
             * Apply a scaling factor that determine which "depth" the height map should reprensent. A value between 0.05 and 0.1 is reasonnable in Parallax, you can reach 0.2 using Parallax Occlusion.
             */
            _this.parallaxScaleBias = 0.05;
            _this._roughness = 0;
            /**
             * In case of refraction, define the value of the indice of refraction.
             * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
             */
            _this.indexOfRefraction = 0.98;
            /**
             * Invert the refraction texture alongside the y axis.
             * It can be usefull with procedural textures or probe for instance.
             * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
             */
            _this.invertRefractionY = true;
            /**
             * Defines the alpha limits in alpha test mode.
             */
            _this.alphaCutOff = 0.4;
            _this._useLightmapAsShadowmap = false;
            _this._useReflectionFresnelFromSpecular = false;
            _this._useGlossinessFromSpecularMapAlpha = false;
            _this._maxSimultaneousLights = 4;
            _this._invertNormalMapX = false;
            _this._invertNormalMapY = false;
            _this._twoSidedLighting = false;
            _this._renderTargets = new BABYLON.SmartArray(16);
            _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
            _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
            // Setup the default processing configuration to the scene.
            _this._attachImageProcessingConfiguration(null);
            _this.getRenderTargetTextures = function () {
                _this._renderTargets.reset();
                if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this._reflectionTexture);
                }
                if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this._refractionTexture);
                }
                return _this._renderTargets;
            };
            return _this;
        }
        Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
            /**
             * Gets the image processing configuration used either in this material.
             */
            get: function () {
                return this._imageProcessingConfiguration;
            },
            /**
             * Sets the Default image processing configuration used either in the this material.
             *
             * If sets to null, the scene one is in use.
             */
            set: function (value) {
                this._attachImageProcessingConfiguration(value);
                // Ensure the effect will be rebuilt.
                this._markAllSubMeshesAsTexturesDirty();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attaches a new image processing configuration to the Standard Material.
         * @param configuration
         */
        StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
            var _this = this;
            if (configuration === this._imageProcessingConfiguration) {
                return;
            }
            // Detaches observer.
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            // Pick the scene configuration if needed.
            if (!configuration) {
                this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
            }
            else {
                this._imageProcessingConfiguration = configuration;
            }
            // Attaches observer.
            if (this._imageProcessingConfiguration) {
                this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
                    _this._markAllSubMeshesAsImageProcessingDirty();
                });
            }
        };
        Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
            /**
             * Gets wether the color curves effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorCurvesEnabled;
            },
            /**
             * Sets wether the color curves effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorCurvesEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
            /**
             * Gets wether the color grading effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorGradingEnabled;
            },
            /**
             * Gets wether the color grading effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorGradingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
            /**
             * Gets wether tonemapping is enabled or not.
             */
            get: function () {
                return this._imageProcessingConfiguration.toneMappingEnabled;
            },
            /**
             * Sets wether tonemapping is enabled or not
             */
            set: function (value) {
                this._imageProcessingConfiguration.toneMappingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            get: function () {
                return this._imageProcessingConfiguration.exposure;
            },
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            set: function (value) {
                this._imageProcessingConfiguration.exposure = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
            /**
             * Gets The camera contrast used on this material.
             */
            get: function () {
                return this._imageProcessingConfiguration.contrast;
            },
            /**
             * Sets The camera contrast used on this material.
             */
            set: function (value) {
                this._imageProcessingConfiguration.contrast = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
            /**
             * Gets the Color Grading 2D Lookup Texture.
             */
            get: function () {
                return this._imageProcessingConfiguration.colorGradingTexture;
            },
            /**
             * Sets the Color Grading 2D Lookup Texture.
             */
            set: function (value) {
                this._imageProcessingConfiguration.colorGradingTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            get: function () {
                return this._imageProcessingConfiguration.colorCurves;
            },
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            set: function (value) {
                this._imageProcessingConfiguration.colorCurves = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
            /**
             * Gets a boolean indicating that current material needs to register RTT
             */
            get: function () {
                if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
                    return true;
                }
                if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
                    return true;
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the current class name of the material e.g. "StandardMaterial"
         * Mainly use in serialization.
         * @returns the class name
         */
        StandardMaterial.prototype.getClassName = function () {
            return "StandardMaterial";
        };
        Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
            /**
             * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
             * You can try switching to logarithmic depth.
             * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
             */
            get: function () {
                return this._useLogarithmicDepth;
            },
            set: function (value) {
                this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
                this._markAllSubMeshesAsMiscDirty();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Specifies if the material will require alpha blending
         * @returns a boolean specifying if alpha blending is needed
         */
        StandardMaterial.prototype.needAlphaBlending = function () {
            return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
        };
        /**
         * Specifies if this material should be rendered in alpha test mode
         * @returns a boolean specifying if an alpha test is needed.
         */
        StandardMaterial.prototype.needAlphaTesting = function () {
            return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
        };
        StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
            return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
        };
        /**
         * Get the texture used for alpha test purpose.
         * @returns the diffuse texture in case of the standard material.
         */
        StandardMaterial.prototype.getAlphaTestTexture = function () {
            return this._diffuseTexture;
        };
        /**
         * Get if the submesh is ready to be used and all its information available.
         * Child classes can use it to update shaders
         * @param mesh defines the mesh to check
         * @param subMesh defines which submesh to check
         * @param useInstances specifies that instances should be used
         * @returns a boolean indicating that the submesh is ready or not
         */
        StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
            if (useInstances === void 0) { useInstances = false; }
            if (subMesh.effect && this.isFrozen) {
                if (this._wasPreviouslyReady) {
                    return true;
                }
            }
            if (!subMesh._materialDefines) {
                subMesh._materialDefines = new StandardMaterialDefines();
            }
            var scene = this.getScene();
            var defines = subMesh._materialDefines;
            if (!this.checkReadyOnEveryCall && subMesh.effect) {
                if (defines._renderId === scene.getRenderId()) {
                    return true;
                }
            }
            var engine = scene.getEngine();
            // Lights
            defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
            // Textures
            if (defines._areTexturesDirty) {
                defines._needUVs = false;
                defines.MAINUV1 = false;
                defines.MAINUV2 = false;
                if (scene.texturesEnabled) {
                    if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
                        if (!this._diffuseTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
                        }
                    }
                    else {
                        defines.DIFFUSE = false;
                    }
                    if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
                        if (!this._ambientTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
                        }
                    }
                    else {
                        defines.AMBIENT = false;
                    }
                    if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
                        if (!this._opacityTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
                            defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
                        }
                    }
                    else {
                        defines.OPACITY = false;
                    }
                    if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
                        if (!this._reflectionTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            defines._needNormals = true;
                            defines.REFLECTION = true;
                            defines.ROUGHNESS = (this._roughness > 0);
                            defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
                            defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
                            defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
                            switch (this._reflectionTexture.coordinatesMode) {
                                case BABYLON.Texture.EXPLICIT_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
                                    break;
                                case BABYLON.Texture.PLANAR_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_PLANAR");
                                    break;
                                case BABYLON.Texture.PROJECTION_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
                                    break;
                                case BABYLON.Texture.SKYBOX_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
                                    defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
                                    break;
                                case BABYLON.Texture.SPHERICAL_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
                                    break;
                                case BABYLON.Texture.EQUIRECTANGULAR_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
                                    break;
                                case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
                                    break;
                                case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                                    defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
                                    break;
                                case BABYLON.Texture.CUBIC_MODE:
                                case BABYLON.Texture.INVCUBIC_MODE:
                                default:
                                    defines.setReflectionMode("REFLECTIONMAP_CUBIC");
                                    break;
                            }
                            defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
                        }
                    }
                    else {
                        defines.REFLECTION = false;
                    }
                    if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
                        if (!this._emissiveTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
                        }
                    }
                    else {
                        defines.EMISSIVE = false;
                    }
                    if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
                        if (!this._lightmapTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
                            defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
                        }
                    }
                    else {
                        defines.LIGHTMAP = false;
                    }
                    if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
                        if (!this._specularTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
                            defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
                        }
                    }
                    else {
                        defines.SPECULAR = false;
                    }
                    if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
                        // Bump texure can not be not blocking.
                        if (!this._bumpTexture.isReady()) {
                            return false;
                        }
                        else {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
                            defines.PARALLAX = this._useParallax;
                            defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
                        }
                        defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
                    }
                    else {
                        defines.BUMP = false;
                    }
                    if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
                        if (!this._refractionTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        else {
                            defines._needUVs = true;
                            defines.REFRACTION = true;
                            defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
                        }
                    }
                    else {
                        defines.REFRACTION = false;
                    }
                    defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
                }
                else {
                    defines.DIFFUSE = false;
                    defines.AMBIENT = false;
                    defines.OPACITY = false;
                    defines.REFLECTION = false;
                    defines.EMISSIVE = false;
                    defines.LIGHTMAP = false;
                    defines.BUMP = false;
                    defines.REFRACTION = false;
                }
                defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
                defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
                defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
                defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
                defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
            }
            if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
                if (!this._imageProcessingConfiguration.isReady()) {
                    return false;
                }
                this._imageProcessingConfiguration.prepareDefines(defines);
                defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
                defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
            }
            if (defines._areFresnelDirty) {
                if (StandardMaterial.FresnelEnabled) {
                    // Fresnel
                    if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
                        this._emissiveFresnelParameters || this._refractionFresnelParameters ||
                        this._reflectionFresnelParameters) {
                        defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
                        defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
                        defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
                        defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
                        defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
                        defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
                        defines._needNormals = true;
                        defines.FRESNEL = true;
                    }
                }
                else {
                    defines.FRESNEL = false;
                }
            }
            // Misc.
            BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
            // Attribs
            BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
            // Values that need to be evaluated on every frame
            BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
            // Get correct effect
            if (defines.isDirty) {
                defines.markAsProcessed();
                scene.resetCachedMaterial();
                // Fallbacks
                var fallbacks = new BABYLON.EffectFallbacks();
                if (defines.REFLECTION) {
                    fallbacks.addFallback(0, "REFLECTION");
                }
                if (defines.SPECULAR) {
                    fallbacks.addFallback(0, "SPECULAR");
                }
                if (defines.BUMP) {
                    fallbacks.addFallback(0, "BUMP");
                }
                if (defines.PARALLAX) {
                    fallbacks.addFallback(1, "PARALLAX");
                }
                if (defines.PARALLAXOCCLUSION) {
                    fallbacks.addFallback(0, "PARALLAXOCCLUSION");
                }
                if (defines.SPECULAROVERALPHA) {
                    fallbacks.addFallback(0, "SPECULAROVERALPHA");
                }
                if (defines.FOG) {
                    fallbacks.addFallback(1, "FOG");
                }
                if (defines.POINTSIZE) {
                    fallbacks.addFallback(0, "POINTSIZE");
                }
                if (defines.LOGARITHMICDEPTH) {
                    fallbacks.addFallback(0, "LOGARITHMICDEPTH");
                }
                BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
                if (defines.SPECULARTERM) {
                    fallbacks.addFallback(0, "SPECULARTERM");
                }
                if (defines.DIFFUSEFRESNEL) {
                    fallbacks.addFallback(1, "DIFFUSEFRESNEL");
                }
                if (defines.OPACITYFRESNEL) {
                    fallbacks.addFallback(2, "OPACITYFRESNEL");
                }
                if (defines.REFLECTIONFRESNEL) {
                    fallbacks.addFallback(3, "REFLECTIONFRESNEL");
                }
                if (defines.EMISSIVEFRESNEL) {
                    fallbacks.addFallback(4, "EMISSIVEFRESNEL");
                }
                if (defines.FRESNEL) {
                    fallbacks.addFallback(4, "FRESNEL");
                }
                //Attributes
                var attribs = [BABYLON.VertexBuffer.PositionKind];
                if (defines.NORMAL) {
                    attribs.push(BABYLON.VertexBuffer.NormalKind);
                }
                if (defines.UV1) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                }
                if (defines.UV2) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                }
                if (defines.VERTEXCOLOR) {
                    attribs.push(BABYLON.VertexBuffer.ColorKind);
                }
                BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
                BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
                BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
                var shaderName = "default";
                var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
                    "vFogInfos", "vFogColor", "pointSize",
                    "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
                    "mBones",
                    "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
                    "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
                    "vReflectionPosition", "vReflectionSize",
                    "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
                ];
                var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
                var uniformBuffers = ["Material", "Scene"];
                if (BABYLON.ImageProcessingConfiguration) {
                    BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
                    BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
                }
                BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
                    uniformsNames: uniforms,
                    uniformBuffersNames: uniformBuffers,
                    samplers: samplers,
                    defines: defines,
                    maxSimultaneousLights: this._maxSimultaneousLights
                });
                if (this.customShaderNameResolve) {
                    shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
                }
                var join = defines.toString();
                subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
                    attributes: attribs,
                    uniformsNames: uniforms,
                    uniformBuffersNames: uniformBuffers,
                    samplers: samplers,
                    defines: join,
                    fallbacks: fallbacks,
                    onCompiled: this.onCompiled,
                    onError: this.onError,
                    indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
                }, engine), defines);
                this.buildUniformLayout();
            }
            if (!subMesh.effect || !subMesh.effect.isReady()) {
                return false;
            }
            defines._renderId = scene.getRenderId();
            this._wasPreviouslyReady = true;
            return true;
        };
        /**
         * Builds the material UBO layouts.
         * Used internally during the effect preparation.
         */
        StandardMaterial.prototype.buildUniformLayout = function () {
            // Order is important !
            this._uniformBuffer.addUniform("diffuseLeftColor", 4);
            this._uniformBuffer.addUniform("diffuseRightColor", 4);
            this._uniformBuffer.addUniform("opacityParts", 4);
            this._uniformBuffer.addUniform("reflectionLeftColor", 4);
            this._uniformBuffer.addUniform("reflectionRightColor", 4);
            this._uniformBuffer.addUniform("refractionLeftColor", 4);
            this._uniformBuffer.addUniform("refractionRightColor", 4);
            this._uniformBuffer.addUniform("emissiveLeftColor", 4);
            this._uniformBuffer.addUniform("emissiveRightColor", 4);
            this._uniformBuffer.addUniform("vDiffuseInfos", 2);
            this._uniformBuffer.addUniform("vAmbientInfos", 2);
            this._uniformBuffer.addUniform("vOpacityInfos", 2);
            this._uniformBuffer.addUniform("vReflectionInfos", 2);
            this._uniformBuffer.addUniform("vReflectionPosition", 3);
            this._uniformBuffer.addUniform("vReflectionSize", 3);
            this._uniformBuffer.addUniform("vEmissiveInfos", 2);
            this._uniformBuffer.addUniform("vLightmapInfos", 2);
            this._uniformBuffer.addUniform("vSpecularInfos", 2);
            this._uniformBuffer.addUniform("vBumpInfos", 3);
            this._uniformBuffer.addUniform("diffuseMatrix", 16);
            this._uniformBuffer.addUniform("ambientMatrix", 16);
            this._uniformBuffer.addUniform("opacityMatrix", 16);
            this._uniformBuffer.addUniform("reflectionMatrix", 16);
            this._uniformBuffer.addUniform("emissiveMatrix", 16);
            this._uniformBuffer.addUniform("lightmapMatrix", 16);
            this._uniformBuffer.addUniform("specularMatrix", 16);
            this._uniformBuffer.addUniform("bumpMatrix", 16);
            this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
            this._uniformBuffer.addUniform("refractionMatrix", 16);
            this._uniformBuffer.addUniform("vRefractionInfos", 4);
            this._uniformBuffer.addUniform("vSpecularColor", 4);
            this._uniformBuffer.addUniform("vEmissiveColor", 3);
            this._uniformBuffer.addUniform("vDiffuseColor", 4);
            this._uniformBuffer.addUniform("pointSize", 1);
            this._uniformBuffer.create();
        };
        /**
         * Unbinds the material from the mesh
         */
        StandardMaterial.prototype.unbind = function () {
            if (this._activeEffect) {
                var needFlag = false;
                if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
                    this._activeEffect.setTexture("reflection2DSampler", null);
                    needFlag = true;
                }
                if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
                    this._activeEffect.setTexture("refraction2DSampler", null);
                    needFlag = true;
                }
                if (needFlag) {
                    this._markAllSubMeshesAsTexturesDirty();
                }
            }
            _super.prototype.unbind.call(this);
        };
        /**
         * Binds the submesh to this material by preparing the effect and shader to draw
         * @param world defines the world transformation matrix
         * @param mesh defines the mesh containing the submesh
         * @param subMesh defines the submesh to bind the material to
         */
        StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
            var scene = this.getScene();
            var defines = subMesh._materialDefines;
            if (!defines) {
                return;
            }
            var effect = subMesh.effect;
            if (!effect) {
                return;
            }
            this._activeEffect = effect;
            // Matrices
            this.bindOnlyWorldMatrix(world);
            // Normal Matrix
            if (defines.OBJECTSPACE_NORMALMAP) {
                world.toNormalMatrix(this._normalMatrix);
                this.bindOnlyNormalMatrix(this._normalMatrix);
            }
            var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
            // Bones
            BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
            if (mustRebind) {
                this._uniformBuffer.bindToEffect(effect, "Material");
                this.bindViewProjection(effect);
                if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
                    if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
                        // Fresnel
                        if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
                            this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
                            this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
                        }
                        if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
                            this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
                        }
                        if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
                            this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
                            this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
                        }
                        if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
                            this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
                            this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
                        }
                        if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
                            this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
                            this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
                        }
                    }
                    // Textures
                    if (scene.texturesEnabled) {
                        if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
                            if (this._diffuseTexture.hasAlpha) {
                                effect.setFloat("alphaCutOff", this.alphaCutOff);
                            }
                        }
                        if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
                        }
                        if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
                        }
                        if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
                            this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
                            if (this._reflectionTexture.boundingBoxSize) {
                                var cubeTexture = this._reflectionTexture;
                                this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
                                this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
                            }
                        }
                        if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
                        }
                        if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
                        }
                        if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
                        }
                        if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
                            this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
                            if (scene._mirroredCameraPosition) {
                                this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
                            }
                            else {
                                this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
                            }
                        }
                        if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
                            var depth = 1.0;
                            if (!this._refractionTexture.isCube) {
                                this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
                                if (this._refractionTexture.depth) {
                                    depth = this._refractionTexture.depth;
                                }
                            }
                            this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
                        }
                    }
                    // Point size
                    if (this.pointsCloud) {
                        this._uniformBuffer.updateFloat("pointSize", this.pointSize);
                    }
                    if (defines.SPECULARTERM) {
                        this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
                    }
                    this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
                    // Diffuse
                    this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
                }
                // Textures
                if (scene.texturesEnabled) {
                    if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
                        effect.setTexture("diffuseSampler", this._diffuseTexture);
                    }
                    if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
                        effect.setTexture("ambientSampler", this._ambientTexture);
                    }
                    if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
                        effect.setTexture("opacitySampler", this._opacityTexture);
                    }
                    if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
                        if (this._reflectionTexture.isCube) {
                            effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
                        }
                        else {
                            effect.setTexture("reflection2DSampler", this._reflectionTexture);
                        }
                    }
                    if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
                        effect.setTexture("emissiveSampler", this._emissiveTexture);
                    }
                    if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
                        effect.setTexture("lightmapSampler", this._lightmapTexture);
                    }
                    if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
                        effect.setTexture("specularSampler", this._specularTexture);
                    }
                    if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
                        effect.setTexture("bumpSampler", this._bumpTexture);
                    }
                    if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
                        var depth = 1.0;
                        if (this._refractionTexture.isCube) {
                            effect.setTexture("refractionCubeSampler", this._refractionTexture);
                        }
                        else {
                            effect.setTexture("refraction2DSampler", this._refractionTexture);
                        }
                    }
                }
                // Clip plane
                BABYLON.MaterialHelper.BindClipPlane(effect, scene);
                // Colors
                scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
                BABYLON.MaterialHelper.BindEyePosition(effect, scene);
                effect.setColor3("vAmbientColor", this._globalAmbientColor);
            }
            if (mustRebind || !this.isFrozen) {
                // Lights
                if (scene.lightsEnabled && !this._disableLighting) {
                    BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
                }
                // View
                if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
                    this.bindView(effect);
                }
                // Fog
                BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
                // Morph targets
                if (defines.NUM_MORPH_INFLUENCERS) {
                    BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
                }
                // Log. depth
                BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
                // image processing
                if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
                    this._imageProcessingConfiguration.bind(this._activeEffect);
                }
            }
            this._uniformBuffer.update();
            this._afterBind(mesh, this._activeEffect);
        };
        /**
         * Get the list of animatables in the material.
         * @returns the list of animatables object used in the material
         */
        StandardMaterial.prototype.getAnimatables = function () {
            var results = [];
            if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
                results.push(this._diffuseTexture);
            }
            if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
                results.push(this._ambientTexture);
            }
            if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
                results.push(this._opacityTexture);
            }
            if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
                results.push(this._reflectionTexture);
            }
            if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
                results.push(this._emissiveTexture);
            }
            if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
                results.push(this._specularTexture);
            }
            if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
                results.push(this._bumpTexture);
            }
            if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
                results.push(this._lightmapTexture);
            }
            if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
                results.push(this._refractionTexture);
            }
            return results;
        };
        /**
         * Gets the active textures from the material
         * @returns an array of textures
         */
        StandardMaterial.prototype.getActiveTextures = function () {
            var activeTextures = _super.prototype.getActiveTextures.call(this);
            if (this._diffuseTexture) {
                activeTextures.push(this._diffuseTexture);
            }
            if (this._ambientTexture) {
                activeTextures.push(this._ambientTexture);
            }
            if (this._opacityTexture) {
                activeTextures.push(this._opacityTexture);
            }
            if (this._reflectionTexture) {
                activeTextures.push(this._reflectionTexture);
            }
            if (this._emissiveTexture) {
                activeTextures.push(this._emissiveTexture);
            }
            if (this._specularTexture) {
                activeTextures.push(this._specularTexture);
            }
            if (this._bumpTexture) {
                activeTextures.push(this._bumpTexture);
            }
            if (this._lightmapTexture) {
                activeTextures.push(this._lightmapTexture);
            }
            if (this._refractionTexture) {
                activeTextures.push(this._refractionTexture);
            }
            return activeTextures;
        };
        /**
         * Specifies if the material uses a texture
         * @param texture defines the texture to check against the material
         * @returns a boolean specifying if the material uses the texture
         */
        StandardMaterial.prototype.hasTexture = function (texture) {
            if (_super.prototype.hasTexture.call(this, texture)) {
                return true;
            }
            if (this._diffuseTexture === texture) {
                return true;
            }
            if (this._ambientTexture === texture) {
                return true;
            }
            if (this._opacityTexture === texture) {
                return true;
            }
            if (this._reflectionTexture === texture) {
                return true;
            }
            if (this._emissiveTexture === texture) {
                return true;
            }
            if (this._specularTexture === texture) {
                return true;
            }
            if (this._bumpTexture === texture) {
                return true;
            }
            if (this._lightmapTexture === texture) {
                return true;
            }
            if (this._refractionTexture === texture) {
                return true;
            }
            return false;
        };
        /**
         * Disposes the material
         * @param forceDisposeEffect specifies if effects should be forcefully disposed
         * @param forceDisposeTextures specifies if textures should be forcefully disposed
         */
        StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeTextures) {
                if (this._diffuseTexture) {
                    this._diffuseTexture.dispose();
                }
                if (this._ambientTexture) {
                    this._ambientTexture.dispose();
                }
                if (this._opacityTexture) {
                    this._opacityTexture.dispose();
                }
                if (this._reflectionTexture) {
                    this._reflectionTexture.dispose();
                }
                if (this._emissiveTexture) {
                    this._emissiveTexture.dispose();
                }
                if (this._specularTexture) {
                    this._specularTexture.dispose();
                }
                if (this._bumpTexture) {
                    this._bumpTexture.dispose();
                }
                if (this._lightmapTexture) {
                    this._lightmapTexture.dispose();
                }
                if (this._refractionTexture) {
                    this._refractionTexture.dispose();
                }
            }
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        /**
         * Makes a duplicate of the material, and gives it a new name
         * @param name defines the new name for the duplicated material
         * @returns the cloned material
         */
        StandardMaterial.prototype.clone = function (name) {
            var _this = this;
            var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
            result.name = name;
            result.id = name;
            return result;
        };
        /**
         * Serializes this material in a JSON representation
         * @returns the serialized material object
         */
        StandardMaterial.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        /**
         * Creates a standard material from parsed material data
         * @param source defines the JSON represnetation of the material
         * @param scene defines the hosting scene
         * @param rootUrl defines the root URL to use to load textures and relative dependencies
         * @returns a new material
         */
        StandardMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
            /**
             * Are diffuse textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._DiffuseTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._DiffuseTextureEnabled === value) {
                    return;
                }
                StandardMaterial._DiffuseTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
            /**
             * Are ambient textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._AmbientTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._AmbientTextureEnabled === value) {
                    return;
                }
                StandardMaterial._AmbientTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
            /**
             * Are opacity textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._OpacityTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._OpacityTextureEnabled === value) {
                    return;
                }
                StandardMaterial._OpacityTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
            /**
             * Are reflection textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._ReflectionTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._ReflectionTextureEnabled === value) {
                    return;
                }
                StandardMaterial._ReflectionTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
            /**
             * Are emissive textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._EmissiveTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._EmissiveTextureEnabled === value) {
                    return;
                }
                StandardMaterial._EmissiveTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
            /**
             * Are specular textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._SpecularTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._SpecularTextureEnabled === value) {
                    return;
                }
                StandardMaterial._SpecularTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
            /**
             * Are bump textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._BumpTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._BumpTextureEnabled === value) {
                    return;
                }
                StandardMaterial._BumpTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
            /**
             * Are lightmap textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._LightmapTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._LightmapTextureEnabled === value) {
                    return;
                }
                StandardMaterial._LightmapTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
            /**
             * Are refraction textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._RefractionTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._RefractionTextureEnabled === value) {
                    return;
                }
                StandardMaterial._RefractionTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
            /**
             * Are color grading textures enabled in the application.
             */
            get: function () {
                return StandardMaterial._ColorGradingTextureEnabled;
            },
            set: function (value) {
                if (StandardMaterial._ColorGradingTextureEnabled === value) {
                    return;
                }
                StandardMaterial._ColorGradingTextureEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardMaterial, "FresnelEnabled", {
            /**
             * Are fresnels enabled in the application.
             */
            get: function () {
                return StandardMaterial._FresnelEnabled;
            },
            set: function (value) {
                if (StandardMaterial._FresnelEnabled === value) {
                    return;
                }
                StandardMaterial._FresnelEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        // Flags used to enable or disable a type of texture for all Standard Materials
        StandardMaterial._DiffuseTextureEnabled = true;
        StandardMaterial._AmbientTextureEnabled = true;
        StandardMaterial._OpacityTextureEnabled = true;
        StandardMaterial._ReflectionTextureEnabled = true;
        StandardMaterial._EmissiveTextureEnabled = true;
        StandardMaterial._SpecularTextureEnabled = true;
        StandardMaterial._BumpTextureEnabled = true;
        StandardMaterial._LightmapTextureEnabled = true;
        StandardMaterial._RefractionTextureEnabled = true;
        StandardMaterial._ColorGradingTextureEnabled = true;
        StandardMaterial._FresnelEnabled = true;
        __decorate([
            BABYLON.serializeAsTexture("diffuseTexture")
        ], StandardMaterial.prototype, "_diffuseTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
        ], StandardMaterial.prototype, "diffuseTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("ambientTexture")
        ], StandardMaterial.prototype, "_ambientTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "ambientTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("opacityTexture")
        ], StandardMaterial.prototype, "_opacityTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
        ], StandardMaterial.prototype, "opacityTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("reflectionTexture")
        ], StandardMaterial.prototype, "_reflectionTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "reflectionTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("emissiveTexture")
        ], StandardMaterial.prototype, "_emissiveTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "emissiveTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("specularTexture")
        ], StandardMaterial.prototype, "_specularTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "specularTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("bumpTexture")
        ], StandardMaterial.prototype, "_bumpTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "bumpTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("lightmapTexture")
        ], StandardMaterial.prototype, "_lightmapTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "lightmapTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("refractionTexture")
        ], StandardMaterial.prototype, "_refractionTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "refractionTexture", void 0);
        __decorate([
            BABYLON.serializeAsColor3("ambient")
        ], StandardMaterial.prototype, "ambientColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("diffuse")
        ], StandardMaterial.prototype, "diffuseColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("specular")
        ], StandardMaterial.prototype, "specularColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("emissive")
        ], StandardMaterial.prototype, "emissiveColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "specularPower", void 0);
        __decorate([
            BABYLON.serialize("useAlphaFromDiffuseTexture")
        ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
        __decorate([
            BABYLON.serialize("useEmissiveAsIllumination")
        ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
        __decorate([
            BABYLON.serialize("linkEmissiveWithDiffuse")
        ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
        __decorate([
            BABYLON.serialize("useSpecularOverAlpha")
        ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
        __decorate([
            BABYLON.serialize("useReflectionOverAlpha")
        ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
        __decorate([
            BABYLON.serialize("disableLighting")
        ], StandardMaterial.prototype, "_disableLighting", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], StandardMaterial.prototype, "disableLighting", void 0);
        __decorate([
            BABYLON.serialize("useObjectSpaceNormalMap")
        ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
        __decorate([
            BABYLON.serialize("useParallax")
        ], StandardMaterial.prototype, "_useParallax", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useParallax", void 0);
        __decorate([
            BABYLON.serialize("useParallaxOcclusion")
        ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
        __decorate([
            BABYLON.serialize("roughness")
        ], StandardMaterial.prototype, "_roughness", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "roughness", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "indexOfRefraction", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "invertRefractionY", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "alphaCutOff", void 0);
        __decorate([
            BABYLON.serialize("useLightmapAsShadowmap")
        ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
        ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
        ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
        ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
        ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
        ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
        ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
        ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
        ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
        __decorate([
            BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
        ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
        ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
        __decorate([
            BABYLON.serialize("useReflectionFresnelFromSpecular")
        ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
        ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
        __decorate([
            BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
        ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
        __decorate([
            BABYLON.serialize("maxSimultaneousLights")
        ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.serialize("invertNormalMapX")
        ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "invertNormalMapX", void 0);
        __decorate([
            BABYLON.serialize("invertNormalMapY")
        ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "invertNormalMapY", void 0);
        __decorate([
            BABYLON.serialize("twoSidedLighting")
        ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], StandardMaterial.prototype, "twoSidedLighting", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardMaterial.prototype, "useLogarithmicDepth", null);
        return StandardMaterial;
    }(BABYLON.PushMaterial));
    BABYLON.StandardMaterial = StandardMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.standardMaterial.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class representing spherical polynomial coefficients to the 3rd degree
     */
    var SphericalPolynomial = /** @class */ (function () {
        function SphericalPolynomial() {
            /**
             * The x coefficients of the spherical polynomial
             */
            this.x = BABYLON.Vector3.Zero();
            /**
             * The y coefficients of the spherical polynomial
             */
            this.y = BABYLON.Vector3.Zero();
            /**
             * The z coefficients of the spherical polynomial
             */
            this.z = BABYLON.Vector3.Zero();
            /**
             * The xx coefficients of the spherical polynomial
             */
            this.xx = BABYLON.Vector3.Zero();
            /**
             * The yy coefficients of the spherical polynomial
             */
            this.yy = BABYLON.Vector3.Zero();
            /**
             * The zz coefficients of the spherical polynomial
             */
            this.zz = BABYLON.Vector3.Zero();
            /**
             * The xy coefficients of the spherical polynomial
             */
            this.xy = BABYLON.Vector3.Zero();
            /**
             * The yz coefficients of the spherical polynomial
             */
            this.yz = BABYLON.Vector3.Zero();
            /**
             * The zx coefficients of the spherical polynomial
             */
            this.zx = BABYLON.Vector3.Zero();
        }
        /**
         * Adds an ambient color to the spherical polynomial
         * @param color the color to add
         */
        SphericalPolynomial.prototype.addAmbient = function (color) {
            var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
            this.xx = this.xx.add(colorVector);
            this.yy = this.yy.add(colorVector);
            this.zz = this.zz.add(colorVector);
        };
        /**
         * Scales the spherical polynomial by the given amount
         * @param scale the amount to scale
         */
        SphericalPolynomial.prototype.scale = function (scale) {
            this.x = this.x.scale(scale);
            this.y = this.y.scale(scale);
            this.z = this.z.scale(scale);
            this.xx = this.xx.scale(scale);
            this.yy = this.yy.scale(scale);
            this.zz = this.zz.scale(scale);
            this.yz = this.yz.scale(scale);
            this.zx = this.zx.scale(scale);
            this.xy = this.xy.scale(scale);
        };
        /**
         * Gets the spherical polynomial from harmonics
         * @param harmonics the spherical harmonics
         * @returns the spherical polynomial
         */
        SphericalPolynomial.FromHarmonics = function (harmonics) {
            var result = new SphericalPolynomial();
            result.x = harmonics.l11.scale(1.02333);
            result.y = harmonics.l1_1.scale(1.02333);
            result.z = harmonics.l10.scale(1.02333);
            result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
            result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
            result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
            result.yz = harmonics.l2_1.scale(0.858086);
            result.zx = harmonics.l21.scale(0.858086);
            result.xy = harmonics.l2_2.scale(0.858086);
            result.scale(1.0 / Math.PI);
            return result;
        };
        /**
         * Constructs a spherical polynomial from an array.
         * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
         * @returns the spherical polynomial
         */
        SphericalPolynomial.FromArray = function (data) {
            var sp = new SphericalPolynomial();
            BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
            BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
            BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
            BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
            BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
            BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
            BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
            BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
            BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
            return sp;
        };
        return SphericalPolynomial;
    }());
    BABYLON.SphericalPolynomial = SphericalPolynomial;
    /**
     * Class representing spherical harmonics coefficients to the 3rd degree
     */
    var SphericalHarmonics = /** @class */ (function () {
        function SphericalHarmonics() {
            /**
             * The l0,0 coefficients of the spherical harmonics
             */
            this.l00 = BABYLON.Vector3.Zero();
            /**
             * The l1,-1 coefficients of the spherical harmonics
             */
            this.l1_1 = BABYLON.Vector3.Zero();
            /**
             * The l1,0 coefficients of the spherical harmonics
             */
            this.l10 = BABYLON.Vector3.Zero();
            /**
             * The l1,1 coefficients of the spherical harmonics
             */
            this.l11 = BABYLON.Vector3.Zero();
            /**
             * The l2,-2 coefficients of the spherical harmonics
             */
            this.l2_2 = BABYLON.Vector3.Zero();
            /**
             * The l2,-1 coefficients of the spherical harmonics
             */
            this.l2_1 = BABYLON.Vector3.Zero();
            /**
             * The l2,0 coefficients of the spherical harmonics
             */
            this.l20 = BABYLON.Vector3.Zero();
            /**
             * The l2,1 coefficients of the spherical harmonics
             */
            this.l21 = BABYLON.Vector3.Zero();
            /**
             * The l2,2 coefficients of the spherical harmonics
             */
            this.lL22 = BABYLON.Vector3.Zero();
        }
        /**
         * Adds a light to the spherical harmonics
         * @param direction the direction of the light
         * @param color the color of the light
         * @param deltaSolidAngle the delta solid angle of the light
         */
        SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
            var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
            var c = colorVector.scale(deltaSolidAngle);
            this.l00 = this.l00.add(c.scale(0.282095));
            this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
            this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
            this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
            this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
            this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
            this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
            this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
            this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
        };
        /**
         * Scales the spherical harmonics by the given amount
         * @param scale the amount to scale
         */
        SphericalHarmonics.prototype.scale = function (scale) {
            this.l00 = this.l00.scale(scale);
            this.l1_1 = this.l1_1.scale(scale);
            this.l10 = this.l10.scale(scale);
            this.l11 = this.l11.scale(scale);
            this.l2_2 = this.l2_2.scale(scale);
            this.l2_1 = this.l2_1.scale(scale);
            this.l20 = this.l20.scale(scale);
            this.l21 = this.l21.scale(scale);
            this.lL22 = this.lL22.scale(scale);
        };
        /**
         * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
         *
         * ```
         * E_lm = A_l * L_lm
         * ```
         *
         * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
         * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
         * the scaling factors are given in equation 9.
         */
        SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
            // Constant (Band 0)
            this.l00 = this.l00.scale(3.141593);
            // Linear (Band 1)
            this.l1_1 = this.l1_1.scale(2.094395);
            this.l10 = this.l10.scale(2.094395);
            this.l11 = this.l11.scale(2.094395);
            // Quadratic (Band 2)
            this.l2_2 = this.l2_2.scale(0.785398);
            this.l2_1 = this.l2_1.scale(0.785398);
            this.l20 = this.l20.scale(0.785398);
            this.l21 = this.l21.scale(0.785398);
            this.lL22 = this.lL22.scale(0.785398);
        };
        /**
         * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
         *
         * ```
         * L = (1/pi) * E * rho
         * ```
         *
         * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
         */
        SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
            this.scale(1.0 / Math.PI);
            // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
            // (The pixel shader must apply albedo after texture fetches, etc).
        };
        /**
         * Gets the spherical harmonics from polynomial
         * @param polynomial the spherical polynomial
         * @returns the spherical harmonics
         */
        SphericalHarmonics.FromPolynomial = function (polynomial) {
            var result = new SphericalHarmonics();
            result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
            result.l1_1 = polynomial.y.scale(0.977204);
            result.l10 = polynomial.z.scale(0.977204);
            result.l11 = polynomial.x.scale(0.977204);
            result.l2_2 = polynomial.xy.scale(1.16538);
            result.l2_1 = polynomial.yz.scale(1.16538);
            result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
            result.l21 = polynomial.zx.scale(1.16538);
            result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
            result.scale(Math.PI);
            return result;
        };
        /**
         * Constructs a spherical harmonics from an array.
         * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
         * @returns the spherical harmonics
         */
        SphericalHarmonics.FromArray = function (data) {
            var sh = new SphericalHarmonics();
            BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
            BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
            BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
            BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
            BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
            BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
            BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
            BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
            BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
            return sh;
        };
        return SphericalHarmonics;
    }());
    BABYLON.SphericalHarmonics = SphericalHarmonics;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sphericalPolynomial.js.map

var BABYLON;
(function (BABYLON) {
    var FileFaceOrientation = /** @class */ (function () {
        function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
            this.name = name;
            this.worldAxisForNormal = worldAxisForNormal;
            this.worldAxisForFileX = worldAxisForFileX;
            this.worldAxisForFileY = worldAxisForFileY;
        }
        return FileFaceOrientation;
    }());
    /**
     * Helper class dealing with the extraction of spherical polynomial dataArray
     * from a cube map.
     */
    var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
        function CubeMapToSphericalPolynomialTools() {
        }
        /**
         * Converts a texture to the according Spherical Polynomial data.
         * This extracts the first 3 orders only as they are the only one used in the lighting.
         *
         * @param texture The texture to extract the information from.
         * @return The Spherical Polynomial data.
         */
        CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
            if (!texture.isCube) {
                // Only supports cube Textures currently.
                return null;
            }
            var size = texture.getSize().width;
            var right = texture.readPixels(0);
            var left = texture.readPixels(1);
            var up;
            var down;
            if (texture.isRenderTarget) {
                up = texture.readPixels(3);
                down = texture.readPixels(2);
            }
            else {
                up = texture.readPixels(2);
                down = texture.readPixels(3);
            }
            var front = texture.readPixels(4);
            var back = texture.readPixels(5);
            var gammaSpace = texture.gammaSpace;
            // Always read as RGBA.
            var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
            var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
                type = BABYLON.Engine.TEXTURETYPE_FLOAT;
            }
            var cubeInfo = {
                size: size,
                right: right,
                left: left,
                up: up,
                down: down,
                front: front,
                back: back,
                format: format,
                type: type,
                gammaSpace: gammaSpace,
            };
            return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
        };
        /**
         * Converts a cubemap to the according Spherical Polynomial data.
         * This extracts the first 3 orders only as they are the only one used in the lighting.
         *
         * @param cubeInfo The Cube map to extract the information from.
         * @return The Spherical Polynomial data.
         */
        CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
            var sphericalHarmonics = new BABYLON.SphericalHarmonics();
            var totalSolidAngle = 0.0;
            // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
            var du = 2.0 / cubeInfo.size;
            var dv = du;
            // The (u,v) of the first texel is half a texel from the corner (-1,-1).
            var minUV = du * 0.5 - 1.0;
            for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
                var fileFace = this.FileFaces[faceIndex];
                var dataArray = cubeInfo[fileFace.name];
                var v = minUV;
                // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
                // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
                // Because SP is still linear, so summation is fine in that basis.
                var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
                for (var y = 0; y < cubeInfo.size; y++) {
                    var u = minUV;
                    for (var x = 0; x < cubeInfo.size; x++) {
                        // World direction (not normalised)
                        var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
                        worldDirection.normalize();
                        var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
                        var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
                        var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
                        var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
                        // Handle Integer types.
                        if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
                            r /= 255;
                            g /= 255;
                            b /= 255;
                        }
                        // Handle Gamma space textures.
                        if (cubeInfo.gammaSpace) {
                            r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
                            g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
                            b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
                        }
                        var color = new BABYLON.Color3(r, g, b);
                        sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
                        totalSolidAngle += deltaSolidAngle;
                        u += du;
                    }
                    v += dv;
                }
            }
            // Solid angle for entire sphere is 4*pi
            var sphereSolidAngle = 4.0 * Math.PI;
            // Adjust the solid angle to allow for how many faces we processed.
            var facesProcessed = 6.0;
            var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
            // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
            // This is needed because the numerical integration over the cube uses a
            // small angle approximation of solid angle for each texel (see deltaSolidAngle),
            // and also to compensate for accumulative error due to float precision in the summation.
            var correctionFactor = expectedSolidAngle / totalSolidAngle;
            sphericalHarmonics.scale(correctionFactor);
            sphericalHarmonics.convertIncidentRadianceToIrradiance();
            sphericalHarmonics.convertIrradianceToLambertianRadiance();
            return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
        };
        CubeMapToSphericalPolynomialTools.FileFaces = [
            new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
            new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
            new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
            new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
            new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
            new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
        ];
        return CubeMapToSphericalPolynomialTools;
    }());
    BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Manages the defines for the PBR Material.
     * @hiddenChildren
     */
    var PBRMaterialDefines = /** @class */ (function (_super) {
        __extends(PBRMaterialDefines, _super);
        /**
         * Initializes the PBR Material defines.
         */
        function PBRMaterialDefines() {
            var _this = _super.call(this) || this;
            _this.PBR = true;
            _this.MAINUV1 = false;
            _this.MAINUV2 = false;
            _this.UV1 = false;
            _this.UV2 = false;
            _this.ALBEDO = false;
            _this.ALBEDODIRECTUV = 0;
            _this.VERTEXCOLOR = false;
            _this.AMBIENT = false;
            _this.AMBIENTDIRECTUV = 0;
            _this.AMBIENTINGRAYSCALE = false;
            _this.OPACITY = false;
            _this.VERTEXALPHA = false;
            _this.OPACITYDIRECTUV = 0;
            _this.OPACITYRGB = false;
            _this.ALPHATEST = false;
            _this.DEPTHPREPASS = false;
            _this.ALPHABLEND = false;
            _this.ALPHAFROMALBEDO = false;
            _this.ALPHATESTVALUE = "0.5";
            _this.SPECULAROVERALPHA = false;
            _this.RADIANCEOVERALPHA = false;
            _this.ALPHAFRESNEL = false;
            _this.LINEARALPHAFRESNEL = false;
            _this.PREMULTIPLYALPHA = false;
            _this.EMISSIVE = false;
            _this.EMISSIVEDIRECTUV = 0;
            _this.REFLECTIVITY = false;
            _this.REFLECTIVITYDIRECTUV = 0;
            _this.SPECULARTERM = false;
            _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
            _this.MICROSURFACEAUTOMATIC = false;
            _this.LODBASEDMICROSFURACE = false;
            _this.MICROSURFACEMAP = false;
            _this.MICROSURFACEMAPDIRECTUV = 0;
            _this.METALLICWORKFLOW = false;
            _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
            _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
            _this.METALLNESSSTOREINMETALMAPBLUE = false;
            _this.AOSTOREINMETALMAPRED = false;
            _this.ENVIRONMENTBRDF = false;
            _this.NORMAL = false;
            _this.TANGENT = false;
            _this.BUMP = false;
            _this.BUMPDIRECTUV = 0;
            _this.OBJECTSPACE_NORMALMAP = false;
            _this.PARALLAX = false;
            _this.PARALLAXOCCLUSION = false;
            _this.NORMALXYSCALE = true;
            _this.LIGHTMAP = false;
            _this.LIGHTMAPDIRECTUV = 0;
            _this.USELIGHTMAPASSHADOWMAP = false;
            _this.GAMMALIGHTMAP = false;
            _this.REFLECTION = false;
            _this.REFLECTIONMAP_3D = false;
            _this.REFLECTIONMAP_SPHERICAL = false;
            _this.REFLECTIONMAP_PLANAR = false;
            _this.REFLECTIONMAP_CUBIC = false;
            _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
            _this.REFLECTIONMAP_PROJECTION = false;
            _this.REFLECTIONMAP_SKYBOX = false;
            _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
            _this.REFLECTIONMAP_EXPLICIT = false;
            _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
            _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
            _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
            _this.INVERTCUBICMAP = false;
            _this.USESPHERICALFROMREFLECTIONMAP = false;
            _this.USESPHERICALINVERTEX = false;
            _this.REFLECTIONMAP_OPPOSITEZ = false;
            _this.LODINREFLECTIONALPHA = false;
            _this.GAMMAREFLECTION = false;
            _this.RGBDREFLECTION = false;
            _this.RADIANCEOCCLUSION = false;
            _this.HORIZONOCCLUSION = false;
            _this.REFRACTION = false;
            _this.REFRACTIONMAP_3D = false;
            _this.REFRACTIONMAP_OPPOSITEZ = false;
            _this.LODINREFRACTIONALPHA = false;
            _this.GAMMAREFRACTION = false;
            _this.RGBDREFRACTION = false;
            _this.LINKREFRACTIONTOTRANSPARENCY = false;
            _this.INSTANCES = false;
            _this.NUM_BONE_INFLUENCERS = 0;
            _this.BonesPerMesh = 0;
            _this.NONUNIFORMSCALING = false;
            _this.MORPHTARGETS = false;
            _this.MORPHTARGETS_NORMAL = false;
            _this.MORPHTARGETS_TANGENT = false;
            _this.NUM_MORPH_INFLUENCERS = 0;
            _this.IMAGEPROCESSING = false;
            _this.VIGNETTE = false;
            _this.VIGNETTEBLENDMODEMULTIPLY = false;
            _this.VIGNETTEBLENDMODEOPAQUE = false;
            _this.TONEMAPPING = false;
            _this.TONEMAPPING_ACES = false;
            _this.CONTRAST = false;
            _this.COLORCURVES = false;
            _this.COLORGRADING = false;
            _this.COLORGRADING3D = false;
            _this.SAMPLER3DGREENDEPTH = false;
            _this.SAMPLER3DBGRMAP = false;
            _this.IMAGEPROCESSINGPOSTPROCESS = false;
            _this.EXPOSURE = false;
            _this.USEPHYSICALLIGHTFALLOFF = false;
            _this.USEGLTFLIGHTFALLOFF = false;
            _this.TWOSIDEDLIGHTING = false;
            _this.SHADOWFLOAT = false;
            _this.CLIPPLANE = false;
            _this.CLIPPLANE2 = false;
            _this.CLIPPLANE3 = false;
            _this.CLIPPLANE4 = false;
            _this.POINTSIZE = false;
            _this.FOG = false;
            _this.LOGARITHMICDEPTH = false;
            _this.FORCENORMALFORWARD = false;
            _this.SPECULARAA = false;
            _this.UNLIT = false;
            _this.rebuild();
            return _this;
        }
        /**
         * Resets the PBR Material defines.
         */
        PBRMaterialDefines.prototype.reset = function () {
            _super.prototype.reset.call(this);
            this.ALPHATESTVALUE = "0.5";
            this.PBR = true;
        };
        return PBRMaterialDefines;
    }(BABYLON.MaterialDefines));
    /**
     * The Physically based material base class of BJS.
     *
     * This offers the main features of a standard PBR material.
     * For more information, please refer to the documentation :
     * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
     */
    var PBRBaseMaterial = /** @class */ (function (_super) {
        __extends(PBRBaseMaterial, _super);
        /**
         * Instantiates a new PBRMaterial instance.
         *
         * @param name The material name
         * @param scene The scene the material will be use in.
         */
        function PBRBaseMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * Intensity of the direct lights e.g. the four lights available in your scene.
             * This impacts both the direct diffuse and specular highlights.
             */
            _this._directIntensity = 1.0;
            /**
             * Intensity of the emissive part of the material.
             * This helps controlling the emissive effect without modifying the emissive color.
             */
            _this._emissiveIntensity = 1.0;
            /**
             * Intensity of the environment e.g. how much the environment will light the object
             * either through harmonics for rough material or through the refelction for shiny ones.
             */
            _this._environmentIntensity = 1.0;
            /**
             * This is a special control allowing the reduction of the specular highlights coming from the
             * four lights of the scene. Those highlights may not be needed in full environment lighting.
             */
            _this._specularIntensity = 1.0;
            /**
             * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
             */
            _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
            /**
             * Debug Control allowing disabling the bump map on this material.
             */
            _this._disableBumpMap = false;
            /**
             * AKA Occlusion Texture Intensity in other nomenclature.
             */
            _this._ambientTextureStrength = 1.0;
            /**
             * Defines how much the AO map is occluding the analytical lights (point spot...).
             * 1 means it completely occludes it
             * 0 mean it has no impact
             */
            _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
            /**
             * The color of a material in ambient lighting.
             */
            _this._ambientColor = new BABYLON.Color3(0, 0, 0);
            /**
             * AKA Diffuse Color in other nomenclature.
             */
            _this._albedoColor = new BABYLON.Color3(1, 1, 1);
            /**
             * AKA Specular Color in other nomenclature.
             */
            _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
            /**
             * The color applied when light is reflected from a material.
             */
            _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
            /**
             * The color applied when light is emitted from a material.
             */
            _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
            /**
             * AKA Glossiness in other nomenclature.
             */
            _this._microSurface = 0.9;
            /**
             * source material index of refraction (IOR)' / 'destination material IOR.
             */
            _this._indexOfRefraction = 0.66;
            /**
             * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
             */
            _this._invertRefractionY = false;
            /**
             * This parameters will make the material used its opacity to control how much it is refracting aginst not.
             * Materials half opaque for instance using refraction could benefit from this control.
             */
            _this._linkRefractionWithTransparency = false;
            /**
             * Specifies that the material will use the light map as a show map.
             */
            _this._useLightmapAsShadowmap = false;
            /**
             * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
             * makes the reflect vector face the model (under horizon).
             */
            _this._useHorizonOcclusion = true;
            /**
             * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
             * too much the area relying on ambient texture to define their ambient occlusion.
             */
            _this._useRadianceOcclusion = true;
            /**
             * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
             */
            _this._useAlphaFromAlbedoTexture = false;
            /**
             * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
             * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
             */
            _this._useSpecularOverAlpha = true;
            /**
             * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
             */
            _this._useMicroSurfaceFromReflectivityMapAlpha = false;
            /**
             * Specifies if the metallic texture contains the roughness information in its alpha channel.
             */
            _this._useRoughnessFromMetallicTextureAlpha = true;
            /**
             * Specifies if the metallic texture contains the roughness information in its green channel.
             */
            _this._useRoughnessFromMetallicTextureGreen = false;
            /**
             * Specifies if the metallic texture contains the metallness information in its blue channel.
             */
            _this._useMetallnessFromMetallicTextureBlue = false;
            /**
             * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
             */
            _this._useAmbientOcclusionFromMetallicTextureRed = false;
            /**
             * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
             */
            _this._useAmbientInGrayScale = false;
            /**
             * In case the reflectivity map does not contain the microsurface information in its alpha channel,
             * The material will try to infer what glossiness each pixel should be.
             */
            _this._useAutoMicroSurfaceFromReflectivityMap = false;
            /**
             * Defines the  falloff type used in this material.
             * It by default is Physical.
             */
            _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
            /**
             * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
             * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
             */
            _this._useRadianceOverAlpha = true;
            /**
             * Allows using an object space normal map (instead of tangent space).
             */
            _this._useObjectSpaceNormalMap = false;
            /**
             * Allows using the bump map in parallax mode.
             */
            _this._useParallax = false;
            /**
             * Allows using the bump map in parallax occlusion mode.
             */
            _this._useParallaxOcclusion = false;
            /**
             * Controls the scale bias of the parallax mode.
             */
            _this._parallaxScaleBias = 0.05;
            /**
             * If sets to true, disables all the lights affecting the material.
             */
            _this._disableLighting = false;
            /**
             * Number of Simultaneous lights allowed on the material.
             */
            _this._maxSimultaneousLights = 4;
            /**
             * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
             */
            _this._invertNormalMapX = false;
            /**
             * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
             */
            _this._invertNormalMapY = false;
            /**
             * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
             */
            _this._twoSidedLighting = false;
            /**
             * Defines the alpha limits in alpha test mode.
             */
            _this._alphaCutOff = 0.4;
            /**
             * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
             */
            _this._forceAlphaTest = false;
            /**
             * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
             * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
             */
            _this._useAlphaFresnel = false;
            /**
             * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
             * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
             */
            _this._useLinearAlphaFresnel = false;
            /**
             * The transparency mode of the material.
             */
            _this._transparencyMode = null;
            /**
             * Specifies the environment BRDF texture used to comput the scale and offset roughness values
             * from cos thetav and roughness:
             * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
             */
            _this._environmentBRDFTexture = null;
            /**
             * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
             */
            _this._forceIrradianceInFragment = false;
            /**
             * Force normal to face away from face.
             */
            _this._forceNormalForward = false;
            /**
             * Enables specular anti aliasing in the PBR shader.
             * It will both interacts on the Geometry for analytical and IBL lighting.
             * It also prefilter the roughness map based on the bump values.
             */
            _this._enableSpecularAntiAliasing = false;
            /**
             * Stores the available render targets.
             */
            _this._renderTargets = new BABYLON.SmartArray(16);
            /**
             * Sets the global ambient color for the material used in lighting calculations.
             */
            _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
            /**
             * If set to true, no lighting calculations will be applied.
             */
            _this._unlit = false;
            // Setup the default processing configuration to the scene.
            _this._attachImageProcessingConfiguration(null);
            _this.getRenderTargetTextures = function () {
                _this._renderTargets.reset();
                if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this._reflectionTexture);
                }
                if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this._refractionTexture);
                }
                return _this._renderTargets;
            };
            _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
            return _this;
        }
        /**
         * Attaches a new image processing configuration to the PBR Material.
         * @param configuration
         */
        PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
            var _this = this;
            if (configuration === this._imageProcessingConfiguration) {
                return;
            }
            // Detaches observer.
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            // Pick the scene configuration if needed.
            if (!configuration) {
                this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
            }
            else {
                this._imageProcessingConfiguration = configuration;
            }
            // Attaches observer.
            if (this._imageProcessingConfiguration) {
                this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
                    _this._markAllSubMeshesAsImageProcessingDirty();
                });
            }
        };
        Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
            /**
             * Gets a boolean indicating that current material needs to register RTT
             */
            get: function () {
                if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
                    return true;
                }
                if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
                    return true;
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the name of the material class.
         */
        PBRBaseMaterial.prototype.getClassName = function () {
            return "PBRBaseMaterial";
        };
        Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
            /**
             * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
             */
            get: function () {
                return this._useLogarithmicDepth;
            },
            /**
             * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
             */
            set: function (value) {
                this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
            /**
             * Gets the current transparency mode.
             */
            get: function () {
                return this._transparencyMode;
            },
            /**
             * Sets the transparency mode of the material.
             *
             * | Value | Type                                | Description |
             * | ----- | ----------------------------------- | ----------- |
             * | 0     | OPAQUE                              |             |
             * | 1     | ALPHATEST                           |             |
             * | 2     | ALPHABLEND                          |             |
             * | 3     | ALPHATESTANDBLEND                   |             |
             *
             */
            set: function (value) {
                if (this._transparencyMode === value) {
                    return;
                }
                this._transparencyMode = value;
                this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
                this._markAllSubMeshesAsTexturesAndMiscDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
            /**
             * Returns true if alpha blending should be disabled.
             */
            get: function () {
                return (this._linkRefractionWithTransparency ||
                    this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
                    this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Specifies whether or not this material should be rendered in alpha blend mode.
         */
        PBRBaseMaterial.prototype.needAlphaBlending = function () {
            if (this._disableAlphaBlending) {
                return false;
            }
            return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
        };
        /**
         * Specifies if the mesh will require alpha blending.
         * @param mesh - BJS mesh.
         */
        PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
            if (this._disableAlphaBlending) {
                return false;
            }
            return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
        };
        /**
         * Specifies whether or not this material should be rendered in alpha test mode.
         */
        PBRBaseMaterial.prototype.needAlphaTesting = function () {
            if (this._forceAlphaTest) {
                return true;
            }
            if (this._linkRefractionWithTransparency) {
                return false;
            }
            return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
        };
        /**
         * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
         */
        PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
            return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
        };
        /**
         * Gets the texture used for the alpha test.
         */
        PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
            return this._albedoTexture;
        };
        /**
         * Specifies that the submesh is ready to be used.
         * @param mesh - BJS mesh.
         * @param subMesh - A submesh of the BJS mesh.  Used to check if it is ready.
         * @param useInstances - Specifies that instances should be used.
         * @returns - boolean indicating that the submesh is ready or not.
         */
        PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
            if (subMesh.effect && this.isFrozen) {
                if (this._wasPreviouslyReady) {
                    return true;
                }
            }
            if (!subMesh._materialDefines) {
                subMesh._materialDefines = new PBRMaterialDefines();
            }
            var defines = subMesh._materialDefines;
            if (!this.checkReadyOnEveryCall && subMesh.effect) {
                if (defines._renderId === this.getScene().getRenderId()) {
                    return true;
                }
            }
            var scene = this.getScene();
            var engine = scene.getEngine();
            if (defines._areTexturesDirty) {
                if (scene.texturesEnabled) {
                    if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                        if (!this._albedoTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
                        if (!this._ambientTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
                        if (!this._opacityTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    var reflectionTexture = this._getReflectionTexture();
                    if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        if (!reflectionTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
                        if (!this._lightmapTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
                        if (!this._emissiveTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
                        if (this._metallicTexture) {
                            if (!this._metallicTexture.isReadyOrNotBlocking()) {
                                return false;
                            }
                        }
                        else if (this._reflectivityTexture) {
                            if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
                                return false;
                            }
                        }
                        if (this._microSurfaceTexture) {
                            if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
                                return false;
                            }
                        }
                    }
                    if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
                        // Bump texture cannot be not blocking.
                        if (!this._bumpTexture.isReady()) {
                            return false;
                        }
                    }
                    var refractionTexture = this._getRefractionTexture();
                    if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
                        if (!refractionTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                    }
                    if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        // This is blocking.
                        if (!this._environmentBRDFTexture.isReady()) {
                            return false;
                        }
                    }
                }
            }
            if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
                if (!this._imageProcessingConfiguration.isReady()) {
                    return false;
                }
            }
            if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                mesh.createNormals(true);
                BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
            }
            var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
            if (effect) {
                scene.resetCachedMaterial();
                subMesh.setEffect(effect, defines);
                this.buildUniformLayout();
            }
            if (!subMesh.effect || !subMesh.effect.isReady()) {
                return false;
            }
            defines._renderId = scene.getRenderId();
            this._wasPreviouslyReady = true;
            return true;
        };
        /**
         * Specifies if the material uses metallic roughness workflow.
         * @returns boolean specifiying if the material uses metallic roughness workflow.
        */
        PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
            if (this._metallic != null || this._roughness != null || this._metallicTexture) {
                return true;
            }
            return false;
        };
        PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
            if (onCompiled === void 0) { onCompiled = null; }
            if (onError === void 0) { onError = null; }
            if (useInstances === void 0) { useInstances = null; }
            if (useClipPlane === void 0) { useClipPlane = null; }
            this._prepareDefines(mesh, defines, useInstances, useClipPlane);
            if (!defines.isDirty) {
                return null;
            }
            defines.markAsProcessed();
            var scene = this.getScene();
            var engine = scene.getEngine();
            // Fallbacks
            var fallbacks = new BABYLON.EffectFallbacks();
            var fallbackRank = 0;
            if (defines.USESPHERICALINVERTEX) {
                fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
            }
            if (defines.FOG) {
                fallbacks.addFallback(fallbackRank, "FOG");
            }
            if (defines.SPECULARAA) {
                fallbacks.addFallback(fallbackRank, "SPECULARAA");
            }
            if (defines.POINTSIZE) {
                fallbacks.addFallback(fallbackRank, "POINTSIZE");
            }
            if (defines.LOGARITHMICDEPTH) {
                fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
            }
            if (defines.PARALLAX) {
                fallbacks.addFallback(fallbackRank, "PARALLAX");
            }
            if (defines.PARALLAXOCCLUSION) {
                fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
            }
            if (defines.ENVIRONMENTBRDF) {
                fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
            }
            if (defines.TANGENT) {
                fallbacks.addFallback(fallbackRank++, "TANGENT");
            }
            if (defines.BUMP) {
                fallbacks.addFallback(fallbackRank++, "BUMP");
            }
            fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
            if (defines.SPECULARTERM) {
                fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
            }
            if (defines.USESPHERICALFROMREFLECTIONMAP) {
                fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
            }
            if (defines.LIGHTMAP) {
                fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
            }
            if (defines.NORMAL) {
                fallbacks.addFallback(fallbackRank++, "NORMAL");
            }
            if (defines.AMBIENT) {
                fallbacks.addFallback(fallbackRank++, "AMBIENT");
            }
            if (defines.EMISSIVE) {
                fallbacks.addFallback(fallbackRank++, "EMISSIVE");
            }
            if (defines.VERTEXCOLOR) {
                fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
            }
            if (defines.NUM_BONE_INFLUENCERS > 0) {
                fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
            }
            if (defines.MORPHTARGETS) {
                fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
            }
            //Attributes
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            if (defines.NORMAL) {
                attribs.push(BABYLON.VertexBuffer.NormalKind);
            }
            if (defines.TANGENT) {
                attribs.push(BABYLON.VertexBuffer.TangentKind);
            }
            if (defines.UV1) {
                attribs.push(BABYLON.VertexBuffer.UVKind);
            }
            if (defines.UV2) {
                attribs.push(BABYLON.VertexBuffer.UV2Kind);
            }
            if (defines.VERTEXCOLOR) {
                attribs.push(BABYLON.VertexBuffer.ColorKind);
            }
            BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
            BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
            BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
            var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
                "vFogInfos", "vFogColor", "pointSize",
                "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
                "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
                "mBones",
                "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
                "vLightingIntensity",
                "logarithmicDepthConstant",
                "vSphericalX", "vSphericalY", "vSphericalZ",
                "vSphericalXX", "vSphericalYY", "vSphericalZZ",
                "vSphericalXY", "vSphericalYZ", "vSphericalZX",
                "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
                "vTangentSpaceParams"
            ];
            var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
                "bumpSampler", "lightmapSampler", "opacitySampler",
                "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
                "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
                "microSurfaceSampler", "environmentBrdfSampler"];
            var uniformBuffers = ["Material", "Scene"];
            if (BABYLON.ImageProcessingConfiguration) {
                BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
                BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
            }
            BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
                uniformsNames: uniforms,
                uniformBuffersNames: uniformBuffers,
                samplers: samplers,
                defines: defines,
                maxSimultaneousLights: this._maxSimultaneousLights
            });
            var join = defines.toString();
            return engine.createEffect("pbr", {
                attributes: attribs,
                uniformsNames: uniforms,
                uniformBuffersNames: uniformBuffers,
                samplers: samplers,
                defines: join,
                fallbacks: fallbacks,
                onCompiled: onCompiled,
                onError: onError,
                indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
            }, engine);
        };
        PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
            if (useInstances === void 0) { useInstances = null; }
            if (useClipPlane === void 0) { useClipPlane = null; }
            var scene = this.getScene();
            var engine = scene.getEngine();
            // Lights
            BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
            defines._needNormals = true;
            // Textures
            defines.METALLICWORKFLOW = this.isMetallicWorkflow();
            if (defines._areTexturesDirty) {
                defines._needUVs = false;
                if (scene.texturesEnabled) {
                    if (scene.getEngine().getCaps().textureLOD) {
                        defines.LODBASEDMICROSFURACE = true;
                    }
                    if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
                    }
                    else {
                        defines.ALBEDO = false;
                    }
                    if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
                        defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
                    }
                    else {
                        defines.AMBIENT = false;
                    }
                    if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
                        defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
                    }
                    else {
                        defines.OPACITY = false;
                    }
                    var reflectionTexture = this._getReflectionTexture();
                    if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        defines.REFLECTION = true;
                        defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
                        defines.RGBDREFLECTION = reflectionTexture.isRGBD;
                        defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
                        defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
                        if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
                            defines.INVERTCUBICMAP = true;
                        }
                        defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
                        switch (reflectionTexture.coordinatesMode) {
                            case BABYLON.Texture.EXPLICIT_MODE:
                                defines.REFLECTIONMAP_EXPLICIT = true;
                                break;
                            case BABYLON.Texture.PLANAR_MODE:
                                defines.REFLECTIONMAP_PLANAR = true;
                                break;
                            case BABYLON.Texture.PROJECTION_MODE:
                                defines.REFLECTIONMAP_PROJECTION = true;
                                break;
                            case BABYLON.Texture.SKYBOX_MODE:
                                defines.REFLECTIONMAP_SKYBOX = true;
                                break;
                            case BABYLON.Texture.SPHERICAL_MODE:
                                defines.REFLECTIONMAP_SPHERICAL = true;
                                break;
                            case BABYLON.Texture.EQUIRECTANGULAR_MODE:
                                defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
                                break;
                            case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
                                defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
                                break;
                            case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                                defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
                                break;
                            case BABYLON.Texture.CUBIC_MODE:
                            case BABYLON.Texture.INVCUBIC_MODE:
                            default:
                                defines.REFLECTIONMAP_CUBIC = true;
                                defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
                                break;
                        }
                        if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
                            if (reflectionTexture.sphericalPolynomial) {
                                defines.USESPHERICALFROMREFLECTIONMAP = true;
                                if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
                                    defines.USESPHERICALINVERTEX = false;
                                }
                                else {
                                    defines.USESPHERICALINVERTEX = true;
                                }
                            }
                        }
                        else {
                            defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
                        }
                    }
                    else {
                        defines.REFLECTION = false;
                        defines.REFLECTIONMAP_3D = false;
                        defines.REFLECTIONMAP_SPHERICAL = false;
                        defines.REFLECTIONMAP_PLANAR = false;
                        defines.REFLECTIONMAP_CUBIC = false;
                        defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
                        defines.REFLECTIONMAP_PROJECTION = false;
                        defines.REFLECTIONMAP_SKYBOX = false;
                        defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
                        defines.REFLECTIONMAP_EXPLICIT = false;
                        defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
                        defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
                        defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
                        defines.INVERTCUBICMAP = false;
                        defines.USESPHERICALFROMREFLECTIONMAP = false;
                        defines.USESPHERICALINVERTEX = false;
                        defines.REFLECTIONMAP_OPPOSITEZ = false;
                        defines.LODINREFLECTIONALPHA = false;
                        defines.GAMMAREFLECTION = false;
                        defines.RGBDREFLECTION = false;
                    }
                    if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
                        defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
                        defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
                    }
                    else {
                        defines.LIGHTMAP = false;
                    }
                    if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
                    }
                    else {
                        defines.EMISSIVE = false;
                    }
                    if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
                        if (this._metallicTexture) {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
                            defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
                            defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
                            defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
                            defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
                        }
                        else if (this._reflectivityTexture) {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
                            defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
                            defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
                        }
                        else {
                            defines.REFLECTIVITY = false;
                        }
                        if (this._microSurfaceTexture) {
                            BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
                        }
                        else {
                            defines.MICROSURFACEMAP = false;
                        }
                    }
                    else {
                        defines.REFLECTIVITY = false;
                        defines.MICROSURFACEMAP = false;
                    }
                    if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
                        if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                            defines.PARALLAX = true;
                            defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
                        }
                        else {
                            defines.PARALLAX = false;
                        }
                        defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
                    }
                    else {
                        defines.BUMP = false;
                    }
                    var refractionTexture = this._getRefractionTexture();
                    if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
                        defines.REFRACTION = true;
                        defines.REFRACTIONMAP_3D = refractionTexture.isCube;
                        defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
                        defines.RGBDREFRACTION = refractionTexture.isRGBD;
                        defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
                        defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
                        if (this._linkRefractionWithTransparency) {
                            defines.LINKREFRACTIONTOTRANSPARENCY = true;
                        }
                    }
                    else {
                        defines.REFRACTION = false;
                    }
                    if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        defines.ENVIRONMENTBRDF = true;
                    }
                    else {
                        defines.ENVIRONMENTBRDF = false;
                    }
                    if (this._shouldUseAlphaFromAlbedoTexture()) {
                        defines.ALPHAFROMALBEDO = true;
                    }
                    else {
                        defines.ALPHAFROMALBEDO = false;
                    }
                }
                defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
                if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
                    defines.USEPHYSICALLIGHTFALLOFF = false;
                    defines.USEGLTFLIGHTFALLOFF = false;
                }
                else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
                    defines.USEPHYSICALLIGHTFALLOFF = false;
                    defines.USEGLTFLIGHTFALLOFF = true;
                }
                else {
                    defines.USEPHYSICALLIGHTFALLOFF = true;
                    defines.USEGLTFLIGHTFALLOFF = false;
                }
                defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
                if (!this.backFaceCulling && this._twoSidedLighting) {
                    defines.TWOSIDEDLIGHTING = true;
                }
                else {
                    defines.TWOSIDEDLIGHTING = false;
                }
                defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
                defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
                defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
                defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
                defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
                defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
            }
            if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
                this._imageProcessingConfiguration.prepareDefines(defines);
            }
            defines.FORCENORMALFORWARD = this._forceNormalForward;
            defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
            defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
            // Misc.
            if (defines._areMiscDirty) {
                BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
                defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
            }
            // Values that need to be evaluated on every frame
            BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
            // Attribs
            BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
        };
        /**
         * Force shader compilation
         */
        PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
            var _this = this;
            var localOptions = __assign({ clipPlane: false }, options);
            var defines = new PBRMaterialDefines();
            var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
            if (effect.isReady()) {
                if (onCompiled) {
                    onCompiled(this);
                }
            }
            else {
                effect.onCompileObservable.add(function () {
                    if (onCompiled) {
                        onCompiled(_this);
                    }
                });
            }
        };
        /**
         * Initializes the uniform buffer layout for the shader.
         */
        PBRBaseMaterial.prototype.buildUniformLayout = function () {
            // Order is important !
            this._uniformBuffer.addUniform("vAlbedoInfos", 2);
            this._uniformBuffer.addUniform("vAmbientInfos", 4);
            this._uniformBuffer.addUniform("vOpacityInfos", 2);
            this._uniformBuffer.addUniform("vEmissiveInfos", 2);
            this._uniformBuffer.addUniform("vLightmapInfos", 2);
            this._uniformBuffer.addUniform("vReflectivityInfos", 3);
            this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
            this._uniformBuffer.addUniform("vRefractionInfos", 4);
            this._uniformBuffer.addUniform("vReflectionInfos", 2);
            this._uniformBuffer.addUniform("vReflectionPosition", 3);
            this._uniformBuffer.addUniform("vReflectionSize", 3);
            this._uniformBuffer.addUniform("vBumpInfos", 3);
            this._uniformBuffer.addUniform("albedoMatrix", 16);
            this._uniformBuffer.addUniform("ambientMatrix", 16);
            this._uniformBuffer.addUniform("opacityMatrix", 16);
            this._uniformBuffer.addUniform("emissiveMatrix", 16);
            this._uniformBuffer.addUniform("lightmapMatrix", 16);
            this._uniformBuffer.addUniform("reflectivityMatrix", 16);
            this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
            this._uniformBuffer.addUniform("bumpMatrix", 16);
            this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
            this._uniformBuffer.addUniform("refractionMatrix", 16);
            this._uniformBuffer.addUniform("reflectionMatrix", 16);
            this._uniformBuffer.addUniform("vReflectionColor", 3);
            this._uniformBuffer.addUniform("vAlbedoColor", 4);
            this._uniformBuffer.addUniform("vLightingIntensity", 4);
            this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
            this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
            this._uniformBuffer.addUniform("vReflectivityColor", 4);
            this._uniformBuffer.addUniform("vEmissiveColor", 3);
            this._uniformBuffer.addUniform("pointSize", 1);
            this._uniformBuffer.create();
        };
        /**
         * Unbinds the textures.
         */
        PBRBaseMaterial.prototype.unbind = function () {
            if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
                this._uniformBuffer.setTexture("reflectionSampler", null);
            }
            if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
                this._uniformBuffer.setTexture("refractionSampler", null);
            }
            _super.prototype.unbind.call(this);
        };
        /**
         * Binds the submesh data.
         * @param world - The world matrix.
         * @param mesh - The BJS mesh.
         * @param subMesh - A submesh of the BJS mesh.
         */
        PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
            var scene = this.getScene();
            var defines = subMesh._materialDefines;
            if (!defines) {
                return;
            }
            var effect = subMesh.effect;
            if (!effect) {
                return;
            }
            this._activeEffect = effect;
            // Matrices
            this.bindOnlyWorldMatrix(world);
            // Normal Matrix
            if (defines.OBJECTSPACE_NORMALMAP) {
                world.toNormalMatrix(this._normalMatrix);
                this.bindOnlyNormalMatrix(this._normalMatrix);
            }
            var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
            // Bones
            BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
            var reflectionTexture = null;
            if (mustRebind) {
                this._uniformBuffer.bindToEffect(effect, "Material");
                this.bindViewProjection(effect);
                reflectionTexture = this._getReflectionTexture();
                var refractionTexture = this._getRefractionTexture();
                if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
                    // Texture uniforms
                    if (scene.texturesEnabled) {
                        if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
                        }
                        if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
                            this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
                        }
                        if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
                        }
                        if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                            this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
                            this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
                            if (reflectionTexture.boundingBoxSize) {
                                var cubeTexture = reflectionTexture;
                                this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
                                this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
                            }
                            var polynomials = reflectionTexture.sphericalPolynomial;
                            if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
                                this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
                                this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
                                this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
                                this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
                                this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
                                this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
                                this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
                                this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
                                this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
                            }
                            this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
                        }
                        if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
                        }
                        if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
                        }
                        if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
                            if (this._metallicTexture) {
                                this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
                                BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
                            }
                            else if (this._reflectivityTexture) {
                                this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
                                BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
                            }
                            if (this._microSurfaceTexture) {
                                this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
                                BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
                            }
                        }
                        if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
                            this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
                            if (scene._mirroredCameraPosition) {
                                this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
                            }
                            else {
                                this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
                            }
                        }
                        if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
                            this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
                            var depth = 1.0;
                            if (!refractionTexture.isCube) {
                                if (refractionTexture.depth) {
                                    depth = refractionTexture.depth;
                                }
                            }
                            this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
                            this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
                        }
                    }
                    // Point size
                    if (this.pointsCloud) {
                        this._uniformBuffer.updateFloat("pointSize", this.pointSize);
                    }
                    // Colors
                    if (defines.METALLICWORKFLOW) {
                        BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
                        BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
                        this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
                    }
                    else {
                        this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
                    }
                    this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
                    this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
                    this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
                    // Misc
                    this._lightingInfos.x = this._directIntensity;
                    this._lightingInfos.y = this._emissiveIntensity;
                    this._lightingInfos.z = this._environmentIntensity;
                    this._lightingInfos.w = this._specularIntensity;
                    this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
                }
                // Textures
                if (scene.texturesEnabled) {
                    if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                        this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
                    }
                    if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
                        this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
                    }
                    if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
                        this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
                    }
                    if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        if (defines.LODBASEDMICROSFURACE) {
                            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
                        }
                        else {
                            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
                            this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
                            this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
                        }
                    }
                    if (defines.ENVIRONMENTBRDF) {
                        this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
                    }
                    if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
                        if (defines.LODBASEDMICROSFURACE) {
                            this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
                        }
                        else {
                            this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
                            this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
                            this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
                        }
                    }
                    if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
                        this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
                    }
                    if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
                        this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
                    }
                    if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
                        if (this._metallicTexture) {
                            this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
                        }
                        else if (this._reflectivityTexture) {
                            this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
                        }
                        if (this._microSurfaceTexture) {
                            this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
                        }
                    }
                    if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
                        this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
                    }
                }
                // Clip plane
                BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
                // Colors
                scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
                var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
                var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
                effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
                effect.setColor3("vAmbientColor", this._globalAmbientColor);
            }
            if (mustRebind || !this.isFrozen) {
                // Lights
                if (scene.lightsEnabled && !this._disableLighting) {
                    BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
                }
                // View
                if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
                    this.bindView(effect);
                }
                // Fog
                BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
                // Morph targets
                if (defines.NUM_MORPH_INFLUENCERS) {
                    BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
                }
                // image processing
                this._imageProcessingConfiguration.bind(this._activeEffect);
                // Log. depth
                BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
            }
            this._uniformBuffer.update();
            this._afterBind(mesh, this._activeEffect);
        };
        /**
         * Returns the animatable textures.
         * @returns - Array of animatable textures.
         */
        PBRBaseMaterial.prototype.getAnimatables = function () {
            var results = [];
            if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
                results.push(this._albedoTexture);
            }
            if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
                results.push(this._ambientTexture);
            }
            if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
                results.push(this._opacityTexture);
            }
            if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
                results.push(this._reflectionTexture);
            }
            if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
                results.push(this._emissiveTexture);
            }
            if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
                results.push(this._metallicTexture);
            }
            else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
                results.push(this._reflectivityTexture);
            }
            if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
                results.push(this._bumpTexture);
            }
            if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
                results.push(this._lightmapTexture);
            }
            if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
                results.push(this._refractionTexture);
            }
            return results;
        };
        /**
         * Returns the texture used for reflections.
         * @returns - Reflection texture if present.  Otherwise, returns the environment texture.
         */
        PBRBaseMaterial.prototype._getReflectionTexture = function () {
            if (this._reflectionTexture) {
                return this._reflectionTexture;
            }
            return this.getScene().environmentTexture;
        };
        /**
         * Returns the texture used for refraction or null if none is used.
         * @returns - Refection texture if present.  If no refraction texture and refraction
         * is linked with transparency, returns environment texture.  Otherwise, returns null.
         */
        PBRBaseMaterial.prototype._getRefractionTexture = function () {
            if (this._refractionTexture) {
                return this._refractionTexture;
            }
            if (this._linkRefractionWithTransparency) {
                return this.getScene().environmentTexture;
            }
            return null;
        };
        /**
         * Disposes the resources of the material.
         * @param forceDisposeEffect - Forces the disposal of effects.
         * @param forceDisposeTextures - Forces the disposal of all textures.
         */
        PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeTextures) {
                if (this._albedoTexture) {
                    this._albedoTexture.dispose();
                }
                if (this._ambientTexture) {
                    this._ambientTexture.dispose();
                }
                if (this._opacityTexture) {
                    this._opacityTexture.dispose();
                }
                if (this._reflectionTexture) {
                    this._reflectionTexture.dispose();
                }
                if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
                    this._environmentBRDFTexture.dispose();
                }
                if (this._emissiveTexture) {
                    this._emissiveTexture.dispose();
                }
                if (this._metallicTexture) {
                    this._metallicTexture.dispose();
                }
                if (this._reflectivityTexture) {
                    this._reflectivityTexture.dispose();
                }
                if (this._bumpTexture) {
                    this._bumpTexture.dispose();
                }
                if (this._lightmapTexture) {
                    this._lightmapTexture.dispose();
                }
                if (this._refractionTexture) {
                    this._refractionTexture.dispose();
                }
            }
            this._renderTargets.dispose();
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        /**
         * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
         */
        PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
        /**
         * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
         * to enhance interoperability with other engines.
         */
        PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
        /**
         * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
         * to enhance interoperability with other materials.
         */
        PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
        /**
         * Stores the reflectivity values based on metallic roughness workflow.
         */
        PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
        __decorate([
            BABYLON.serializeAsImageProcessingConfiguration()
        ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
        __decorate([
            BABYLON.serialize()
        ], PBRBaseMaterial.prototype, "transparencyMode", null);
        return PBRBaseMaterial;
    }(BABYLON.PushMaterial));
    BABYLON.PBRBaseMaterial = PBRBaseMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pbrBaseMaterial.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * The Physically based simple base material of BJS.
     *
     * This enables better naming and convention enforcements on top of the pbrMaterial.
     * It is used as the base class for both the specGloss and metalRough conventions.
     */
    var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
        __extends(PBRBaseSimpleMaterial, _super);
        /**
         * Instantiates a new PBRMaterial instance.
         *
         * @param name The material name
         * @param scene The scene the material will be use in.
         */
        function PBRBaseSimpleMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * Number of Simultaneous lights allowed on the material.
             */
            _this.maxSimultaneousLights = 4;
            /**
             * If sets to true, disables all the lights affecting the material.
             */
            _this.disableLighting = false;
            /**
             * If sets to true, x component of normal map value will invert (x = 1.0 - x).
             */
            _this.invertNormalMapX = false;
            /**
             * If sets to true, y component of normal map value will invert (y = 1.0 - y).
             */
            _this.invertNormalMapY = false;
            /**
             * Emissivie color used to self-illuminate the model.
             */
            _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
            /**
             * Occlusion Channel Strenght.
             */
            _this.occlusionStrength = 1.0;
            /**
             * If true, the light map contains occlusion information instead of lighting info.
             */
            _this.useLightmapAsShadowmap = false;
            _this._useAlphaFromAlbedoTexture = true;
            _this._useAmbientInGrayScale = true;
            return _this;
        }
        Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
            /**
             * Gets the current double sided mode.
             */
            get: function () {
                return this._twoSidedLighting;
            },
            /**
             * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
             */
            set: function (value) {
                if (this._twoSidedLighting === value) {
                    return;
                }
                this._twoSidedLighting = value;
                this.backFaceCulling = !value;
                this._markAllSubMeshesAsTexturesDirty();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Return the active textures of the material.
         */
        PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
            var activeTextures = _super.prototype.getActiveTextures.call(this);
            if (this.environmentTexture) {
                activeTextures.push(this.environmentTexture);
            }
            if (this.normalTexture) {
                activeTextures.push(this.normalTexture);
            }
            if (this.emissiveTexture) {
                activeTextures.push(this.emissiveTexture);
            }
            if (this.occlusionTexture) {
                activeTextures.push(this.occlusionTexture);
            }
            if (this.lightmapTexture) {
                activeTextures.push(this.lightmapTexture);
            }
            return activeTextures;
        };
        PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
            if (_super.prototype.hasTexture.call(this, texture)) {
                return true;
            }
            if (this.lightmapTexture === texture) {
                return true;
            }
            return false;
        };
        PBRBaseSimpleMaterial.prototype.getClassName = function () {
            return "PBRBaseSimpleMaterial";
        };
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
        ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
        ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
        __decorate([
            BABYLON.serializeAsColor3("emissive"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
        ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
        ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
        ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
        ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
        return PBRBaseSimpleMaterial;
    }(BABYLON.PBRBaseMaterial));
    BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * The Physically based material of BJS.
     *
     * This offers the main features of a standard PBR material.
     * For more information, please refer to the documentation :
     * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
     */
    var PBRMaterial = /** @class */ (function (_super) {
        __extends(PBRMaterial, _super);
        /**
         * Instantiates a new PBRMaterial instance.
         *
         * @param name The material name
         * @param scene The scene the material will be use in.
         */
        function PBRMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * Intensity of the direct lights e.g. the four lights available in your scene.
             * This impacts both the direct diffuse and specular highlights.
             */
            _this.directIntensity = 1.0;
            /**
             * Intensity of the emissive part of the material.
             * This helps controlling the emissive effect without modifying the emissive color.
             */
            _this.emissiveIntensity = 1.0;
            /**
             * Intensity of the environment e.g. how much the environment will light the object
             * either through harmonics for rough material or through the refelction for shiny ones.
             */
            _this.environmentIntensity = 1.0;
            /**
             * This is a special control allowing the reduction of the specular highlights coming from the
             * four lights of the scene. Those highlights may not be needed in full environment lighting.
             */
            _this.specularIntensity = 1.0;
            /**
             * Debug Control allowing disabling the bump map on this material.
             */
            _this.disableBumpMap = false;
            /**
             * AKA Occlusion Texture Intensity in other nomenclature.
             */
            _this.ambientTextureStrength = 1.0;
            /**
             * Defines how much the AO map is occluding the analytical lights (point spot...).
             * 1 means it completely occludes it
             * 0 mean it has no impact
             */
            _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
            /**
             * The color of a material in ambient lighting.
             */
            _this.ambientColor = new BABYLON.Color3(0, 0, 0);
            /**
             * AKA Diffuse Color in other nomenclature.
             */
            _this.albedoColor = new BABYLON.Color3(1, 1, 1);
            /**
             * AKA Specular Color in other nomenclature.
             */
            _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
            /**
             * The color reflected from the material.
             */
            _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
            /**
             * The color emitted from the material.
             */
            _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
            /**
             * AKA Glossiness in other nomenclature.
             */
            _this.microSurface = 1.0;
            /**
             * source material index of refraction (IOR)' / 'destination material IOR.
             */
            _this.indexOfRefraction = 0.66;
            /**
             * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
             */
            _this.invertRefractionY = false;
            /**
             * This parameters will make the material used its opacity to control how much it is refracting aginst not.
             * Materials half opaque for instance using refraction could benefit from this control.
             */
            _this.linkRefractionWithTransparency = false;
            /**
             * If true, the light map contains occlusion information instead of lighting info.
             */
            _this.useLightmapAsShadowmap = false;
            /**
             * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
             */
            _this.useAlphaFromAlbedoTexture = false;
            /**
             * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
             */
            _this.forceAlphaTest = false;
            /**
             * Defines the alpha limits in alpha test mode.
             */
            _this.alphaCutOff = 0.4;
            /**
             * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
             * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
             */
            _this.useSpecularOverAlpha = true;
            /**
             * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
             */
            _this.useMicroSurfaceFromReflectivityMapAlpha = false;
            /**
             * Specifies if the metallic texture contains the roughness information in its alpha channel.
             */
            _this.useRoughnessFromMetallicTextureAlpha = true;
            /**
             * Specifies if the metallic texture contains the roughness information in its green channel.
             */
            _this.useRoughnessFromMetallicTextureGreen = false;
            /**
             * Specifies if the metallic texture contains the metallness information in its blue channel.
             */
            _this.useMetallnessFromMetallicTextureBlue = false;
            /**
             * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
             */
            _this.useAmbientOcclusionFromMetallicTextureRed = false;
            /**
             * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
             */
            _this.useAmbientInGrayScale = false;
            /**
             * In case the reflectivity map does not contain the microsurface information in its alpha channel,
             * The material will try to infer what glossiness each pixel should be.
             */
            _this.useAutoMicroSurfaceFromReflectivityMap = false;
            /**
             * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
             * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
             */
            _this.useRadianceOverAlpha = true;
            /**
             * Allows using an object space normal map (instead of tangent space).
             */
            _this.useObjectSpaceNormalMap = false;
            /**
             * Allows using the bump map in parallax mode.
             */
            _this.useParallax = false;
            /**
             * Allows using the bump map in parallax occlusion mode.
             */
            _this.useParallaxOcclusion = false;
            /**
             * Controls the scale bias of the parallax mode.
             */
            _this.parallaxScaleBias = 0.05;
            /**
             * If sets to true, disables all the lights affecting the material.
             */
            _this.disableLighting = false;
            /**
             * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
             */
            _this.forceIrradianceInFragment = false;
            /**
             * Number of Simultaneous lights allowed on the material.
             */
            _this.maxSimultaneousLights = 4;
            /**
             * If sets to true, x component of normal map value will invert (x = 1.0 - x).
             */
            _this.invertNormalMapX = false;
            /**
             * If sets to true, y component of normal map value will invert (y = 1.0 - y).
             */
            _this.invertNormalMapY = false;
            /**
             * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
             */
            _this.twoSidedLighting = false;
            /**
             * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
             * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
             */
            _this.useAlphaFresnel = false;
            /**
             * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
             * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
             */
            _this.useLinearAlphaFresnel = false;
            /**
             * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
             * And/Or occlude the blended part.
             */
            _this.environmentBRDFTexture = null;
            /**
             * Force normal to face away from face.
             */
            _this.forceNormalForward = false;
            /**
             * Enables specular anti aliasing in the PBR shader.
             * It will both interacts on the Geometry for analytical and IBL lighting.
             * It also prefilter the roughness map based on the bump values.
             */
            _this.enableSpecularAntiAliasing = false;
            /**
             * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
             * makes the reflect vector face the model (under horizon).
             */
            _this.useHorizonOcclusion = true;
            /**
             * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
             * too much the area relying on ambient texture to define their ambient occlusion.
             */
            _this.useRadianceOcclusion = true;
            /**
             * If set to true, no lighting calculations will be applied.
             */
            _this.unlit = false;
            _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
            return _this;
        }
        Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
            /**
             * BJS is using an harcoded light falloff based on a manually sets up range.
             * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
             * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
             */
            get: function () {
                return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
            },
            /**
             * BJS is using an harcoded light falloff based on a manually sets up range.
             * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
             * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
             */
            set: function (value) {
                if (value !== this.usePhysicalLightFalloff) {
                    // Ensure the effect will be rebuilt.
                    this._markAllSubMeshesAsTexturesDirty();
                    if (value) {
                        this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
                    }
                    else {
                        this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
            /**
             * In order to support the falloff compatibility with gltf, a special mode has been added
             * to reproduce the gltf light falloff.
             */
            get: function () {
                return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
            },
            /**
             * In order to support the falloff compatibility with gltf, a special mode has been added
             * to reproduce the gltf light falloff.
             */
            set: function (value) {
                if (value !== this.useGLTFLightFalloff) {
                    // Ensure the effect will be rebuilt.
                    this._markAllSubMeshesAsTexturesDirty();
                    if (value) {
                        this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
                    }
                    else {
                        this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
            /**
             * Gets the image processing configuration used either in this material.
             */
            get: function () {
                return this._imageProcessingConfiguration;
            },
            /**
             * Sets the Default image processing configuration used either in the this material.
             *
             * If sets to null, the scene one is in use.
             */
            set: function (value) {
                this._attachImageProcessingConfiguration(value);
                // Ensure the effect will be rebuilt.
                this._markAllSubMeshesAsTexturesDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
            /**
             * Gets wether the color curves effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorCurvesEnabled;
            },
            /**
             * Sets wether the color curves effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorCurvesEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
            /**
             * Gets wether the color grading effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorGradingEnabled;
            },
            /**
             * Gets wether the color grading effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorGradingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
            /**
             * Gets wether tonemapping is enabled or not.
             */
            get: function () {
                return this._imageProcessingConfiguration.toneMappingEnabled;
            },
            /**
             * Sets wether tonemapping is enabled or not
             */
            set: function (value) {
                this._imageProcessingConfiguration.toneMappingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            get: function () {
                return this._imageProcessingConfiguration.exposure;
            },
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            set: function (value) {
                this._imageProcessingConfiguration.exposure = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
            /**
             * Gets The camera contrast used on this material.
             */
            get: function () {
                return this._imageProcessingConfiguration.contrast;
            },
            /**
             * Sets The camera contrast used on this material.
             */
            set: function (value) {
                this._imageProcessingConfiguration.contrast = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
            /**
             * Gets the Color Grading 2D Lookup Texture.
             */
            get: function () {
                return this._imageProcessingConfiguration.colorGradingTexture;
            },
            /**
             * Sets the Color Grading 2D Lookup Texture.
             */
            set: function (value) {
                this._imageProcessingConfiguration.colorGradingTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            get: function () {
                return this._imageProcessingConfiguration.colorCurves;
            },
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            set: function (value) {
                this._imageProcessingConfiguration.colorCurves = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the name of this material class.
         */
        PBRMaterial.prototype.getClassName = function () {
            return "PBRMaterial";
        };
        /**
         * Returns an array of the actively used textures.
         * @returns - Array of BaseTextures
         */
        PBRMaterial.prototype.getActiveTextures = function () {
            var activeTextures = _super.prototype.getActiveTextures.call(this);
            if (this._albedoTexture) {
                activeTextures.push(this._albedoTexture);
            }
            if (this._ambientTexture) {
                activeTextures.push(this._ambientTexture);
            }
            if (this._opacityTexture) {
                activeTextures.push(this._opacityTexture);
            }
            if (this._reflectionTexture) {
                activeTextures.push(this._reflectionTexture);
            }
            if (this._emissiveTexture) {
                activeTextures.push(this._emissiveTexture);
            }
            if (this._reflectivityTexture) {
                activeTextures.push(this._reflectivityTexture);
            }
            if (this._metallicTexture) {
                activeTextures.push(this._metallicTexture);
            }
            if (this._microSurfaceTexture) {
                activeTextures.push(this._microSurfaceTexture);
            }
            if (this._bumpTexture) {
                activeTextures.push(this._bumpTexture);
            }
            if (this._lightmapTexture) {
                activeTextures.push(this._lightmapTexture);
            }
            if (this._refractionTexture) {
                activeTextures.push(this._refractionTexture);
            }
            return activeTextures;
        };
        /**
         * Checks to see if a texture is used in the material.
         * @param texture - Base texture to use.
         * @returns - Boolean specifying if a texture is used in the material.
         */
        PBRMaterial.prototype.hasTexture = function (texture) {
            if (_super.prototype.hasTexture.call(this, texture)) {
                return true;
            }
            if (this._albedoTexture === texture) {
                return true;
            }
            if (this._ambientTexture === texture) {
                return true;
            }
            if (this._opacityTexture === texture) {
                return true;
            }
            if (this._reflectionTexture === texture) {
                return true;
            }
            if (this._reflectivityTexture === texture) {
                return true;
            }
            if (this._metallicTexture === texture) {
                return true;
            }
            if (this._microSurfaceTexture === texture) {
                return true;
            }
            if (this._bumpTexture === texture) {
                return true;
            }
            if (this._lightmapTexture === texture) {
                return true;
            }
            if (this._refractionTexture === texture) {
                return true;
            }
            return false;
        };
        /**
         * Makes a duplicate of the current material.
         * @param name - name to use for the new material.
         */
        PBRMaterial.prototype.clone = function (name) {
            var _this = this;
            var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
            clone.id = name;
            clone.name = name;
            return clone;
        };
        /**
         * Serializes this PBR Material.
         * @returns - An object with the serialized material.
         */
        PBRMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.PBRMaterial";
            return serializationObject;
        };
        // Statics
        /**
         * Parses a PBR Material from a serialized object.
         * @param source - Serialized object.
         * @param scene - BJS scene instance.
         * @param rootUrl - url for the scene object
         * @returns - PBRMaterial
         */
        PBRMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        /**
         * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
         */
        PBRMaterial.PBRMATERIAL_OPAQUE = 0;
        /**
         * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
         */
        PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
        /**
         * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
         */
        PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
        /**
         * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
         * They are also discarded below the alpha cutoff threshold to improve performances.
         */
        PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
        /**
         * Defines the default value of how much AO map is occluding the analytical lights
         * (point spot...).
         */
        PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "directIntensity", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "emissiveIntensity", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "environmentIntensity", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "specularIntensity", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "disableBumpMap", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "albedoTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "ambientTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
        ], PBRMaterial.prototype, "opacityTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "reflectionTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "emissiveTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "reflectivityTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "metallicTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "metallic", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "roughness", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "bumpTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
        ], PBRMaterial.prototype, "lightmapTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "refractionTexture", void 0);
        __decorate([
            BABYLON.serializeAsColor3("ambient"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "ambientColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("albedo"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "albedoColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("reflectivity"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "reflectivityColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("reflection"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "reflectionColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3("emissive"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "emissiveColor", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "microSurface", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "indexOfRefraction", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "invertRefractionY", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
        ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
        ], PBRMaterial.prototype, "forceAlphaTest", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
        ], PBRMaterial.prototype, "alphaCutOff", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
        __decorate([
            BABYLON.serialize()
        ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useParallax", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], PBRMaterial.prototype, "disableLighting", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "invertNormalMapX", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "invertNormalMapY", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "twoSidedLighting", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "forceNormalForward", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
        ], PBRMaterial.prototype, "unlit", void 0);
        return PBRMaterial;
    }(BABYLON.PBRBaseMaterial));
    BABYLON.PBRMaterial = PBRMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pbrMaterial.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * The PBR material of BJS following the metal roughness convention.
     *
     * This fits to the PBR convention in the GLTF definition:
     * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
     */
    var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
        __extends(PBRMetallicRoughnessMaterial, _super);
        /**
         * Instantiates a new PBRMetalRoughnessMaterial instance.
         *
         * @param name The material name
         * @param scene The scene the material will be use in.
         */
        function PBRMetallicRoughnessMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._useRoughnessFromMetallicTextureAlpha = false;
            _this._useRoughnessFromMetallicTextureGreen = true;
            _this._useMetallnessFromMetallicTextureBlue = true;
            _this.metallic = 1.0;
            _this.roughness = 1.0;
            return _this;
        }
        /**
         * Return the currrent class name of the material.
         */
        PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
            return "PBRMetallicRoughnessMaterial";
        };
        /**
         * Return the active textures of the material.
         */
        PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
            var activeTextures = _super.prototype.getActiveTextures.call(this);
            if (this.baseTexture) {
                activeTextures.push(this.baseTexture);
            }
            if (this.metallicRoughnessTexture) {
                activeTextures.push(this.metallicRoughnessTexture);
            }
            return activeTextures;
        };
        /**
         * Checks to see if a texture is used in the material.
         * @param texture - Base texture to use.
         * @returns - Boolean specifying if a texture is used in the material.
         */
        PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
            if (_super.prototype.hasTexture.call(this, texture)) {
                return true;
            }
            if (this.baseTexture === texture) {
                return true;
            }
            if (this.metallicRoughnessTexture === texture) {
                return true;
            }
            return false;
        };
        /**
         * Makes a duplicate of the current material.
         * @param name - name to use for the new material.
         */
        PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
            var _this = this;
            var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
            clone.id = name;
            clone.name = name;
            return clone;
        };
        /**
         * Serialize the material to a parsable JSON object.
         */
        PBRMetallicRoughnessMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
            return serializationObject;
        };
        /**
         * Parses a JSON object correponding to the serialize function.
         */
        PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        __decorate([
            BABYLON.serializeAsColor3(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
        ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
        ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
        ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
        return PBRMetallicRoughnessMaterial;
    }(BABYLON.PBRBaseSimpleMaterial));
    BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * The PBR material of BJS following the specular glossiness convention.
     *
     * This fits to the PBR convention in the GLTF definition:
     * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
     */
    var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
        __extends(PBRSpecularGlossinessMaterial, _super);
        /**
         * Instantiates a new PBRSpecularGlossinessMaterial instance.
         *
         * @param name The material name
         * @param scene The scene the material will be use in.
         */
        function PBRSpecularGlossinessMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._useMicroSurfaceFromReflectivityMapAlpha = true;
            return _this;
        }
        /**
         * Return the currrent class name of the material.
         */
        PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
            return "PBRSpecularGlossinessMaterial";
        };
        /**
         * Return the active textures of the material.
         */
        PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
            var activeTextures = _super.prototype.getActiveTextures.call(this);
            if (this.diffuseTexture) {
                activeTextures.push(this.diffuseTexture);
            }
            if (this.specularGlossinessTexture) {
                activeTextures.push(this.specularGlossinessTexture);
            }
            return activeTextures;
        };
        /**
         * Checks to see if a texture is used in the material.
         * @param texture - Base texture to use.
         * @returns - Boolean specifying if a texture is used in the material.
         */
        PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
            if (_super.prototype.hasTexture.call(this, texture)) {
                return true;
            }
            if (this.diffuseTexture === texture) {
                return true;
            }
            if (this.specularGlossinessTexture === texture) {
                return true;
            }
            return false;
        };
        /**
         * Makes a duplicate of the current material.
         * @param name - name to use for the new material.
         */
        PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
            var _this = this;
            var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
            clone.id = name;
            clone.name = name;
            return clone;
        };
        /**
         * Serialize the material to a parsable JSON object.
         */
        PBRSpecularGlossinessMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
            return serializationObject;
        };
        /**
         * Parses a JSON object correponding to the serialize function.
         */
        PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        __decorate([
            BABYLON.serializeAsColor3("diffuse"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
        ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
        ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
        __decorate([
            BABYLON.serializeAsColor3("specular"),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
        ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
        __decorate([
            BABYLON.serialize(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
        ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
        __decorate([
            BABYLON.serializeAsTexture(),
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
        ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
        return PBRSpecularGlossinessMaterial;
    }(BABYLON.PBRBaseSimpleMaterial));
    BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @ignore
     * This is a list of all the different input types that are available in the application.
     * Fo instance: ArcRotateCameraGamepadInput...
     */
    BABYLON.CameraInputTypes = {};
    /**
     * This represents the input manager used within a camera.
     * It helps dealing with all the different kind of input attached to a camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var CameraInputsManager = /** @class */ (function () {
        /**
         * Instantiate a new Camera Input Manager.
         * @param camera Defines the camera the input manager blongs to
         */
        function CameraInputsManager(camera) {
            this.attached = {};
            this.camera = camera;
            this.checkInputs = function () { };
        }
        /**
         * Add an input method to a camera
         * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
         * @param input camera input method
         */
        CameraInputsManager.prototype.add = function (input) {
            var type = input.getSimpleName();
            if (this.attached[type]) {
                BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
                return;
            }
            this.attached[type] = input;
            input.camera = this.camera;
            //for checkInputs, we are dynamically creating a function
            //the goal is to avoid the performance penalty of looping for inputs in the render loop
            if (input.checkInputs) {
                this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
            }
            if (this.attachedElement) {
                input.attachControl(this.attachedElement);
            }
        };
        /**
         * Remove a specific input method from a camera
         * example: camera.inputs.remove(camera.inputs.attached.mouse);
         * @param inputToRemove camera input method
         */
        CameraInputsManager.prototype.remove = function (inputToRemove) {
            for (var cam in this.attached) {
                var input = this.attached[cam];
                if (input === inputToRemove) {
                    input.detachControl(this.attachedElement);
                    input.camera = null;
                    delete this.attached[cam];
                    this.rebuildInputCheck();
                }
            }
        };
        /**
         * Remove a specific input type from a camera
         * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
         * @param inputType the type of the input to remove
         */
        CameraInputsManager.prototype.removeByType = function (inputType) {
            for (var cam in this.attached) {
                var input = this.attached[cam];
                if (input.getClassName() === inputType) {
                    input.detachControl(this.attachedElement);
                    input.camera = null;
                    delete this.attached[cam];
                    this.rebuildInputCheck();
                }
            }
        };
        CameraInputsManager.prototype._addCheckInputs = function (fn) {
            var current = this.checkInputs;
            return function () {
                current();
                fn();
            };
        };
        /**
         * Attach the input controls to the currently attached dom element to listen the events from.
         * @param input Defines the input to attach
         */
        CameraInputsManager.prototype.attachInput = function (input) {
            if (this.attachedElement) {
                input.attachControl(this.attachedElement, this.noPreventDefault);
            }
        };
        /**
         * Attach the current manager inputs controls to a specific dom element to listen the events from.
         * @param element Defines the dom element to collect the events from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
            if (noPreventDefault === void 0) { noPreventDefault = false; }
            if (this.attachedElement) {
                return;
            }
            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
            this.attachedElement = element;
            this.noPreventDefault = noPreventDefault;
            for (var cam in this.attached) {
                this.attached[cam].attachControl(element, noPreventDefault);
            }
        };
        /**
         * Detach the current manager inputs controls from a specific dom element.
         * @param element Defines the dom element to collect the events from
         * @param disconnect Defines whether the input should be removed from the current list of attached inputs
         */
        CameraInputsManager.prototype.detachElement = function (element, disconnect) {
            if (disconnect === void 0) { disconnect = false; }
            if (this.attachedElement !== element) {
                return;
            }
            for (var cam in this.attached) {
                this.attached[cam].detachControl(element);
                if (disconnect) {
                    this.attached[cam].camera = null;
                }
            }
            this.attachedElement = null;
        };
        /**
         * Rebuild the dynamic inputCheck function from the current list of
         * defined inputs in the manager.
         */
        CameraInputsManager.prototype.rebuildInputCheck = function () {
            this.checkInputs = function () { };
            for (var cam in this.attached) {
                var input = this.attached[cam];
                if (input.checkInputs) {
                    this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
                }
            }
        };
        /**
         * Remove all attached input methods from a camera
         */
        CameraInputsManager.prototype.clear = function () {
            if (this.attachedElement) {
                this.detachElement(this.attachedElement, true);
            }
            this.attached = {};
            this.attachedElement = null;
            this.checkInputs = function () { };
        };
        /**
         * Serialize the current input manager attached to a camera.
         * This ensures than once parsed,
         * the input associated to the camera will be identical to the current ones
         * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
         */
        CameraInputsManager.prototype.serialize = function (serializedCamera) {
            var inputs = {};
            for (var cam in this.attached) {
                var input = this.attached[cam];
                var res = BABYLON.SerializationHelper.Serialize(input);
                inputs[input.getClassName()] = res;
            }
            serializedCamera.inputsmgr = inputs;
        };
        /**
         * Parses an input manager serialized JSON to restore the previous list of inputs
         * and states associated to a camera.
         * @param parsedCamera Defines the JSON to parse
         */
        CameraInputsManager.prototype.parse = function (parsedCamera) {
            var parsedInputs = parsedCamera.inputsmgr;
            if (parsedInputs) {
                this.clear();
                for (var n in parsedInputs) {
                    var construct = BABYLON.CameraInputTypes[n];
                    if (construct) {
                        var parsedinput = parsedInputs[n];
                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
                        this.add(input);
                    }
                }
            }
            else {
                //2016-03-08 this part is for managing backward compatibility
                for (var n in this.attached) {
                    var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
                    if (construct) {
                        var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
                        this.remove(this.attached[n]);
                        this.add(input);
                    }
                }
            }
        };
        return CameraInputsManager;
    }());
    BABYLON.CameraInputsManager = CameraInputsManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.cameraInputsManager.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * A target camera takes a mesh or position as a target and continues to look at it while it moves.
     * This is the base of the follow, arc rotate cameras and Free camera
     * @see http://doc.babylonjs.com/features/cameras
     */
    var TargetCamera = /** @class */ (function (_super) {
        __extends(TargetCamera, _super);
        /**
         * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
         * This is the base of the follow, arc rotate cameras and Free camera
         * @see http://doc.babylonjs.com/features/cameras
         * @param name Defines the name of the camera in the scene
         * @param position Defines the start position of the camera in the scene
         * @param scene Defines the scene the camera belongs to
         * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
         */
        function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
            if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
            var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
            /**
             * Define the current direction the camera is moving to
             */
            _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
            /**
             * Define the current rotation the camera is rotating to
             */
            _this.cameraRotation = new BABYLON.Vector2(0, 0);
            /**
             * Define the current rotation of the camera
             */
            _this.rotation = new BABYLON.Vector3(0, 0, 0);
            /**
             * Define the current speed of the camera
             */
            _this.speed = 2.0;
            /**
             * Add cconstraint to the camera to prevent it to move freely in all directions and
             * around all axis.
             */
            _this.noRotationConstraint = false;
            /**
             * Define the current target of the camera as an object or a position.
             */
            _this.lockedTarget = null;
            /** @hidden */
            _this._currentTarget = BABYLON.Vector3.Zero();
            /** @hidden */
            _this._viewMatrix = BABYLON.Matrix.Zero();
            /** @hidden */
            _this._camMatrix = BABYLON.Matrix.Zero();
            /** @hidden */
            _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
            /** @hidden */
            _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
            /** @hidden */
            _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
            /** @hidden */
            _this._transformedReferencePoint = BABYLON.Vector3.Zero();
            _this._globalCurrentTarget = BABYLON.Vector3.Zero();
            _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
            _this._defaultUp = BABYLON.Vector3.Up();
            _this._cachedRotationZ = 0;
            _this._cachedQuaternionRotationZ = 0;
            return _this;
        }
        /**
         * Gets the position in front of the camera at a given distance.
         * @param distance The distance from the camera we want the position to be
         * @returns the position
         */
        TargetCamera.prototype.getFrontPosition = function (distance) {
            this.getWorldMatrix();
            var direction = this.getTarget().subtract(this.position);
            direction.normalize();
            direction.scaleInPlace(distance);
            return this.globalPosition.add(direction);
        };
        /** @hidden */
        TargetCamera.prototype._getLockedTargetPosition = function () {
            if (!this.lockedTarget) {
                return null;
            }
            if (this.lockedTarget.absolutePosition) {
                this.lockedTarget.computeWorldMatrix();
            }
            return this.lockedTarget.absolutePosition || this.lockedTarget;
        };
        /**
         * Store current camera state of the camera (fov, position, rotation, etc..)
         * @returns the camera
         */
        TargetCamera.prototype.storeState = function () {
            this._storedPosition = this.position.clone();
            this._storedRotation = this.rotation.clone();
            if (this.rotationQuaternion) {
                this._storedRotationQuaternion = this.rotationQuaternion.clone();
            }
            return _super.prototype.storeState.call(this);
        };
        /**
         * Restored camera state. You must call storeState() first
         * @returns whether it was successful or not
         * @hidden
         */
        TargetCamera.prototype._restoreStateValues = function () {
            if (!_super.prototype._restoreStateValues.call(this)) {
                return false;
            }
            this.position = this._storedPosition.clone();
            this.rotation = this._storedRotation.clone();
            if (this.rotationQuaternion) {
                this.rotationQuaternion = this._storedRotationQuaternion.clone();
            }
            this.cameraDirection.copyFromFloats(0, 0, 0);
            this.cameraRotation.copyFromFloats(0, 0);
            return true;
        };
        /** @hidden */
        TargetCamera.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
        };
        /** @hidden */
        TargetCamera.prototype._updateCache = function (ignoreParentClass) {
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            var lockedTargetPosition = this._getLockedTargetPosition();
            if (!lockedTargetPosition) {
                this._cache.lockedTarget = null;
            }
            else {
                if (!this._cache.lockedTarget) {
                    this._cache.lockedTarget = lockedTargetPosition.clone();
                }
                else {
                    this._cache.lockedTarget.copyFrom(lockedTargetPosition);
                }
            }
            this._cache.rotation.copyFrom(this.rotation);
            if (this.rotationQuaternion) {
                this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
            }
        };
        // Synchronized
        /** @hidden */
        TargetCamera.prototype._isSynchronizedViewMatrix = function () {
            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
                return false;
            }
            var lockedTargetPosition = this._getLockedTargetPosition();
            return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
                && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
        };
        // Methods
        /** @hidden */
        TargetCamera.prototype._computeLocalCameraSpeed = function () {
            var engine = this.getEngine();
            return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
        };
        // Target
        /** @hidden */
        TargetCamera.prototype.setTarget = function (target) {
            this.upVector.normalize();
            if (this.position.z === target.z) {
                this.position.z += BABYLON.Epsilon;
            }
            BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
            this._camMatrix.invert();
            this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
            var vDir = target.subtract(this.position);
            if (vDir.x >= 0.0) {
                this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
            }
            else {
                this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
            }
            this.rotation.z = 0;
            if (isNaN(this.rotation.x)) {
                this.rotation.x = 0;
            }
            if (isNaN(this.rotation.y)) {
                this.rotation.y = 0;
            }
            if (isNaN(this.rotation.z)) {
                this.rotation.z = 0;
            }
            if (this.rotationQuaternion) {
                BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
            }
        };
        /**
         * Return the current target position of the camera. This value is expressed in local space.
         * @returns the target position
         */
        TargetCamera.prototype.getTarget = function () {
            return this._currentTarget;
        };
        /** @hidden */
        TargetCamera.prototype._decideIfNeedsToMove = function () {
            return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
        };
        /** @hidden */
        TargetCamera.prototype._updatePosition = function () {
            if (this.parent) {
                this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
                BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
                this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
                return;
            }
            this.position.addInPlace(this.cameraDirection);
        };
        /** @hidden */
        TargetCamera.prototype._checkInputs = function () {
            var needToMove = this._decideIfNeedsToMove();
            var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
            // Move
            if (needToMove) {
                this._updatePosition();
            }
            // Rotate
            if (needToRotate) {
                this.rotation.x += this.cameraRotation.x;
                this.rotation.y += this.cameraRotation.y;
                //rotate, if quaternion is set and rotation was used
                if (this.rotationQuaternion) {
                    var len = this.rotation.lengthSquared();
                    if (len) {
                        BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
                    }
                }
                if (!this.noRotationConstraint) {
                    var limit = (Math.PI / 2) * 0.95;
                    if (this.rotation.x > limit) {
                        this.rotation.x = limit;
                    }
                    if (this.rotation.x < -limit) {
                        this.rotation.x = -limit;
                    }
                }
            }
            // Inertia
            if (needToMove) {
                if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
                    this.cameraDirection.x = 0;
                }
                if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
                    this.cameraDirection.y = 0;
                }
                if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
                    this.cameraDirection.z = 0;
                }
                this.cameraDirection.scaleInPlace(this.inertia);
            }
            if (needToRotate) {
                if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
                    this.cameraRotation.x = 0;
                }
                if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
                    this.cameraRotation.y = 0;
                }
                this.cameraRotation.scaleInPlace(this.inertia);
            }
            _super.prototype._checkInputs.call(this);
        };
        TargetCamera.prototype._updateCameraRotationMatrix = function () {
            if (this.rotationQuaternion) {
                this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
            }
            else {
                BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
            }
        };
        /**
         * Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
         * @returns the current camera
         */
        TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
            BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
            return this;
        };
        /** @hidden */
        TargetCamera.prototype._getViewMatrix = function () {
            if (this.lockedTarget) {
                this.setTarget(this._getLockedTargetPosition());
            }
            // Compute
            this._updateCameraRotationMatrix();
            // Apply the changed rotation to the upVector
            if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
                this._rotateUpVectorWithCameraRotationMatrix();
                this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
            }
            else if (this._cachedRotationZ != this.rotation.z) {
                this._rotateUpVectorWithCameraRotationMatrix();
                this._cachedRotationZ = this.rotation.z;
            }
            BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
            // Computing target and final matrix
            this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
            this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
            return this._viewMatrix;
        };
        TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
            if (this.parent) {
                var parentWorldMatrix = this.parent.getWorldMatrix();
                BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
                BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
                BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
                this._markSyncedWithParent();
            }
            else {
                this._globalPosition.copyFrom(position);
                this._globalCurrentTarget.copyFrom(target);
                this._globalCurrentUpVector.copyFrom(up);
            }
            if (this.getScene().useRightHandedSystem) {
                BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
            }
            else {
                BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
            }
        };
        /**
         * @hidden
         */
        TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
            if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
                var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
                if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
                    if (!this.rotationQuaternion) {
                        this.rotationQuaternion = new BABYLON.Quaternion();
                    }
                    rigCamera._cameraRigParams = {};
                    rigCamera.rotationQuaternion = new BABYLON.Quaternion();
                }
                return rigCamera;
            }
            return null;
        };
        /**
         * @hidden
         */
        TargetCamera.prototype._updateRigCameras = function () {
            var camLeft = this._rigCameras[0];
            var camRight = this._rigCameras[1];
            switch (this.cameraRigMode) {
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                    //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
                    var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
                    var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
                    this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
                    camLeft.setTarget(this.getTarget());
                    camRight.setTarget(this.getTarget());
                    break;
                case BABYLON.Camera.RIG_MODE_VR:
                    if (camLeft.rotationQuaternion) {
                        camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
                        camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
                    }
                    else {
                        camLeft.rotation.copyFrom(this.rotation);
                        camRight.rotation.copyFrom(this.rotation);
                    }
                    camLeft.position.copyFrom(this.position);
                    camRight.position.copyFrom(this.position);
                    break;
            }
            _super.prototype._updateRigCameras.call(this);
        };
        TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
            if (!this._rigCamTransformMatrix) {
                this._rigCamTransformMatrix = new BABYLON.Matrix();
            }
            var target = this.getTarget();
            BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
            this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
            BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
        };
        /**
         * Gets the current object class name.
         * @return the class name
         */
        TargetCamera.prototype.getClassName = function () {
            return "TargetCamera";
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], TargetCamera.prototype, "rotation", void 0);
        __decorate([
            BABYLON.serialize()
        ], TargetCamera.prototype, "speed", void 0);
        __decorate([
            BABYLON.serializeAsMeshReference("lockedTargetId")
        ], TargetCamera.prototype, "lockedTarget", void 0);
        return TargetCamera;
    }(BABYLON.Camera));
    BABYLON.TargetCamera = TargetCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.targetCamera.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the mouse inputs to control the movement of a free camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraMouseInput = /** @class */ (function () {
        /**
         * Manage the mouse inputs to control the movement of a free camera.
         * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
         * @param touchEnabled Defines if touch is enabled or not
         */
        function FreeCameraMouseInput(
        /**
         * Define if touch is enabled in the mouse input
         */
        touchEnabled) {
            if (touchEnabled === void 0) { touchEnabled = true; }
            this.touchEnabled = touchEnabled;
            /**
             * Defines the buttons associated with the input to handle camera move.
             */
            this.buttons = [0, 1, 2];
            /**
             * Defines the pointer angular sensibility  along the X and Y axis or how fast is the camera rotating.
             */
            this.angularSensibility = 2000.0;
            this.previousPosition = null;
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var engine = this.camera.getEngine();
            if (!this._pointerInput) {
                this._pointerInput = function (p, s) {
                    var evt = p.event;
                    if (engine.isInVRExclusivePointerMode) {
                        return;
                    }
                    if (!_this.touchEnabled && evt.pointerType === "touch") {
                        return;
                    }
                    if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
                        return;
                    }
                    var srcElement = (evt.srcElement || evt.target);
                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
                        try {
                            srcElement.setPointerCapture(evt.pointerId);
                        }
                        catch (e) {
                            //Nothing to do with the error. Execution will continue.
                        }
                        _this.previousPosition = {
                            x: evt.clientX,
                            y: evt.clientY
                        };
                        if (!noPreventDefault) {
                            evt.preventDefault();
                            element.focus();
                        }
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
                        try {
                            srcElement.releasePointerCapture(evt.pointerId);
                        }
                        catch (e) {
                            //Nothing to do with the error.
                        }
                        _this.previousPosition = null;
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
                        if (!_this.previousPosition || engine.isPointerLock) {
                            return;
                        }
                        var offsetX = evt.clientX - _this.previousPosition.x;
                        if (_this.camera.getScene().useRightHandedSystem) {
                            offsetX *= -1;
                        }
                        if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
                            offsetX *= -1;
                        }
                        _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
                        var offsetY = evt.clientY - _this.previousPosition.y;
                        _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
                        _this.previousPosition = {
                            x: evt.clientX,
                            y: evt.clientY
                        };
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                };
            }
            this._onMouseMove = function (evt) {
                if (!engine.isPointerLock) {
                    return;
                }
                if (engine.isInVRExclusivePointerMode) {
                    return;
                }
                var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
                if (_this.camera.getScene().useRightHandedSystem) {
                    offsetX *= -1;
                }
                if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) {
                    offsetX *= -1;
                }
                _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
                var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
                _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
                _this.previousPosition = null;
                if (!noPreventDefault) {
                    evt.preventDefault();
                }
            };
            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
            element.addEventListener("mousemove", this._onMouseMove, false);
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCameraMouseInput.prototype.detachControl = function (element) {
            if (this._observer && element) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                if (this._onMouseMove) {
                    element.removeEventListener("mousemove", this._onMouseMove);
                }
                this._observer = null;
                this._onMouseMove = null;
                this.previousPosition = null;
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        FreeCameraMouseInput.prototype.getClassName = function () {
            return "FreeCameraMouseInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        FreeCameraMouseInput.prototype.getSimpleName = function () {
            return "mouse";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraMouseInput.prototype, "buttons", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
        return FreeCameraMouseInput;
    }());
    BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
    BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraMouseInput.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the keyboard inputs to control the movement of a free camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraKeyboardMoveInput = /** @class */ (function () {
        function FreeCameraKeyboardMoveInput() {
            /**
             * Gets or Set the list of keyboard keys used to control the forward move of the camera.
             */
            this.keysUp = [38];
            /**
             * Gets or Set the list of keyboard keys used to control the backward move of the camera.
             */
            this.keysDown = [40];
            /**
             * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
             */
            this.keysLeft = [37];
            /**
             * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
             */
            this.keysRight = [39];
            this._keys = new Array();
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            if (this._onCanvasBlurObserver) {
                return;
            }
            this._scene = this.camera.getScene();
            this._engine = this._scene.getEngine();
            this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
                _this._keys = [];
            });
            this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
                var evt = info.event;
                if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
                        var index = _this._keys.indexOf(evt.keyCode);
                        if (index === -1) {
                            _this._keys.push(evt.keyCode);
                        }
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                }
                else {
                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                        _this.keysRight.indexOf(evt.keyCode) !== -1) {
                        var index = _this._keys.indexOf(evt.keyCode);
                        if (index >= 0) {
                            _this._keys.splice(index, 1);
                        }
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                    }
                }
            });
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
            if (this._scene) {
                if (this._onKeyboardObserver) {
                    this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
                }
                if (this._onCanvasBlurObserver) {
                    this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
                }
                this._onKeyboardObserver = null;
                this._onCanvasBlurObserver = null;
            }
            this._keys = [];
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
            if (this._onKeyboardObserver) {
                var camera = this.camera;
                // Keyboard
                for (var index = 0; index < this._keys.length; index++) {
                    var keyCode = this._keys[index];
                    var speed = camera._computeLocalCameraSpeed();
                    if (this.keysLeft.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(-speed, 0, 0);
                    }
                    else if (this.keysUp.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(0, 0, speed);
                    }
                    else if (this.keysRight.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(speed, 0, 0);
                    }
                    else if (this.keysDown.indexOf(keyCode) !== -1) {
                        camera._localDirection.copyFromFloats(0, 0, -speed);
                    }
                    if (camera.getScene().useRightHandedSystem) {
                        camera._localDirection.z *= -1;
                    }
                    camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
                    BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
                    camera.cameraDirection.addInPlace(camera._transformedDirection);
                }
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
            return "FreeCameraKeyboardMoveInput";
        };
        /** @hidden */
        FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
            this._keys = [];
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
            return "keyboard";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
        return FreeCameraKeyboardMoveInput;
    }());
    BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
    BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Default Inputs manager for the FreeCamera.
     * It groups all the default supported inputs for ease of use.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraInputsManager = /** @class */ (function (_super) {
        __extends(FreeCameraInputsManager, _super);
        /**
         * Instantiates a new FreeCameraInputsManager.
         * @param camera Defines the camera the inputs belong to
         */
        function FreeCameraInputsManager(camera) {
            return _super.call(this, camera) || this;
        }
        /**
         * Add keyboard input support to the input manager.
         * @returns the current input manager
         */
        FreeCameraInputsManager.prototype.addKeyboard = function () {
            this.add(new BABYLON.FreeCameraKeyboardMoveInput());
            return this;
        };
        /**
         * Add mouse input support to the input manager.
         * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
         * @returns the current input manager
         */
        FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
            if (touchEnabled === void 0) { touchEnabled = true; }
            this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
            return this;
        };
        /**
         * Add orientation input support to the input manager.
         * @returns the current input manager
         */
        FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
            this.add(new BABYLON.FreeCameraDeviceOrientationInput());
            return this;
        };
        /**
         * Add touch input support to the input manager.
         * @returns the current input manager
         */
        FreeCameraInputsManager.prototype.addTouch = function () {
            this.add(new BABYLON.FreeCameraTouchInput());
            return this;
        };
        /**
         * Add virtual joystick input support to the input manager.
         * @returns the current input manager
         */
        FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
            this.add(new BABYLON.FreeCameraVirtualJoystickInput());
            return this;
        };
        return FreeCameraInputsManager;
    }(BABYLON.CameraInputsManager));
    BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraInputsManager.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
        // Forcing to use the Universal camera
        return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
     * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
     * @see http://doc.babylonjs.com/features/cameras#universal-camera
     */
    var FreeCamera = /** @class */ (function (_super) {
        __extends(FreeCamera, _super);
        /**
         * Instantiates a Free Camera.
         * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
         * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
         * @see http://doc.babylonjs.com/features/cameras#universal-camera
         * @param name Define the name of the camera in the scene
         * @param position Define the start position of the camera in the scene
         * @param scene Define the scene the camera belongs to
         * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
         */
        function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
            if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
            var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
            /**
             * Define the collision ellipsoid of the camera.
             * This is helpful to simulate a camera body like the player body around the camera
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
             */
            _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
            /**
             * Define an offset for the position of the ellipsoid around the camera.
             * This can be helpful to determine the center of the body near the gravity center of the body
             * instead of its head.
             */
            _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
            /**
             * Enable or disable collisions of the camera with the rest of the scene objects.
             */
            _this.checkCollisions = false;
            /**
             * Enable or disable gravity on the camera.
             */
            _this.applyGravity = false;
            _this._needMoveForGravity = false;
            _this._oldPosition = BABYLON.Vector3.Zero();
            _this._diffPosition = BABYLON.Vector3.Zero();
            _this._newPosition = BABYLON.Vector3.Zero();
            // Collisions
            _this._collisionMask = -1;
            _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
                if (collidedMesh === void 0) { collidedMesh = null; }
                //TODO move this to the collision coordinator!
                if (_this.getScene().workerCollisions) {
                    newPosition.multiplyInPlace(_this._collider._radius);
                }
                var updatePosition = function (newPos) {
                    _this._newPosition.copyFrom(newPos);
                    _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
                    if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
                        _this.position.addInPlace(_this._diffPosition);
                        if (_this.onCollide && collidedMesh) {
                            _this.onCollide(collidedMesh);
                        }
                    }
                };
                updatePosition(newPosition);
            };
            _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
            _this.inputs.addKeyboard().addMouse();
            return _this;
        }
        Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
            /**
             * Gets the input sensibility for a mouse input. (default is 2000.0)
             * Higher values reduce sensitivity.
             */
            get: function () {
                var mouse = this.inputs.attached["mouse"];
                if (mouse) {
                    return mouse.angularSensibility;
                }
                return 0;
            },
            /**
             * Sets the input sensibility for a mouse input. (default is 2000.0)
             * Higher values reduce sensitivity.
             */
            set: function (value) {
                var mouse = this.inputs.attached["mouse"];
                if (mouse) {
                    mouse.angularSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysUp", {
            /**
             * Gets or Set the list of keyboard keys used to control the forward move of the camera.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysUp;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysUp = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysDown", {
            /**
             * Gets or Set the list of keyboard keys used to control the backward move of the camera.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysDown;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysDown = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysLeft", {
            /**
             * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysLeft;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysLeft = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FreeCamera.prototype, "keysRight", {
            /**
             * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysRight;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysRight = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attached controls to the current camera.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
            this.inputs.attachElement(element, noPreventDefault);
        };
        /**
         * Detach the current controls from the camera.
         * The camera will stop reacting to inputs.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCamera.prototype.detachControl = function (element) {
            this.inputs.detachElement(element);
            this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
            this.cameraRotation = new BABYLON.Vector2(0, 0);
        };
        Object.defineProperty(FreeCamera.prototype, "collisionMask", {
            /**
             * Define a collision mask to limit the list of object the camera can collide with
             */
            get: function () {
                return this._collisionMask;
            },
            set: function (mask) {
                this._collisionMask = !isNaN(mask) ? mask : -1;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        FreeCamera.prototype._collideWithWorld = function (displacement) {
            var globalPosition;
            if (this.parent) {
                globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
            }
            else {
                globalPosition = this.position;
            }
            globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
            this._oldPosition.addInPlace(this.ellipsoidOffset);
            if (!this._collider) {
                this._collider = new BABYLON.Collider();
            }
            this._collider._radius = this.ellipsoid;
            this._collider.collisionMask = this._collisionMask;
            //no need for clone, as long as gravity is not on.
            var actualDisplacement = displacement;
            //add gravity to the direction to prevent the dual-collision checking
            if (this.applyGravity) {
                //this prevents mending with cameraDirection, a global variable of the free camera class.
                actualDisplacement = displacement.add(this.getScene().gravity);
            }
            this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
        };
        /** @hidden */
        FreeCamera.prototype._checkInputs = function () {
            if (!this._localDirection) {
                this._localDirection = BABYLON.Vector3.Zero();
                this._transformedDirection = BABYLON.Vector3.Zero();
            }
            this.inputs.checkInputs();
            _super.prototype._checkInputs.call(this);
        };
        /** @hidden */
        FreeCamera.prototype._decideIfNeedsToMove = function () {
            return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
        };
        /** @hidden */
        FreeCamera.prototype._updatePosition = function () {
            if (this.checkCollisions && this.getScene().collisionsEnabled) {
                this._collideWithWorld(this.cameraDirection);
            }
            else {
                _super.prototype._updatePosition.call(this);
            }
        };
        /**
         * Destroy the camera and release the current resources hold by it.
         */
        FreeCamera.prototype.dispose = function () {
            this.inputs.clear();
            _super.prototype.dispose.call(this);
        };
        /**
         * Gets the current object class name.
         * @return the class name
         */
        FreeCamera.prototype.getClassName = function () {
            return "FreeCamera";
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], FreeCamera.prototype, "ellipsoid", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], FreeCamera.prototype, "ellipsoidOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCamera.prototype, "checkCollisions", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCamera.prototype, "applyGravity", void 0);
        return FreeCamera;
    }(BABYLON.TargetCamera));
    BABYLON.FreeCamera = FreeCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCamera.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the keyboard inputs to control the movement of an arc rotate camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
        function ArcRotateCameraKeyboardMoveInput() {
            /**
             * Defines the list of key codes associated with the up action (increase alpha)
             */
            this.keysUp = [38];
            /**
             * Defines the list of key codes associated with the down action (decrease alpha)
             */
            this.keysDown = [40];
            /**
             * Defines the list of key codes associated with the left action (increase beta)
             */
            this.keysLeft = [37];
            /**
             * Defines the list of key codes associated with the right action (decrease beta)
             */
            this.keysRight = [39];
            /**
             * Defines the list of key codes associated with the reset action.
             * Those keys reset the camera to its last stored state (with the method camera.storeState())
             */
            this.keysReset = [220];
            /**
             * Defines the panning sensibility of the inputs.
             * (How fast is the camera paning)
             */
            this.panningSensibility = 50.0;
            /**
             * Defines the zooming sensibility of the inputs.
             * (How fast is the camera zooming)
             */
            this.zoomingSensibility = 25.0;
            /**
             * Defines wether maintaining the alt key down switch the movement mode from
             * orientation to zoom.
             */
            this.useAltToZoom = true;
            /**
             * Rotation speed of the camera
             */
            this.angularSpeed = 0.01;
            this._keys = new Array();
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            if (this._onCanvasBlurObserver) {
                return;
            }
            this._scene = this.camera.getScene();
            this._engine = this._scene.getEngine();
            this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
                _this._keys = [];
            });
            this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
                var evt = info.event;
                if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
                    _this._ctrlPressed = evt.ctrlKey;
                    _this._altPressed = evt.altKey;
                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                        _this.keysRight.indexOf(evt.keyCode) !== -1 ||
                        _this.keysReset.indexOf(evt.keyCode) !== -1) {
                        var index = _this._keys.indexOf(evt.keyCode);
                        if (index === -1) {
                            _this._keys.push(evt.keyCode);
                        }
                        if (evt.preventDefault) {
                            if (!noPreventDefault) {
                                evt.preventDefault();
                            }
                        }
                    }
                }
                else {
                    if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
                        _this.keysDown.indexOf(evt.keyCode) !== -1 ||
                        _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
                        _this.keysRight.indexOf(evt.keyCode) !== -1 ||
                        _this.keysReset.indexOf(evt.keyCode) !== -1) {
                        var index = _this._keys.indexOf(evt.keyCode);
                        if (index >= 0) {
                            _this._keys.splice(index, 1);
                        }
                        if (evt.preventDefault) {
                            if (!noPreventDefault) {
                                evt.preventDefault();
                            }
                        }
                    }
                }
            });
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
            if (this._scene) {
                if (this._onKeyboardObserver) {
                    this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
                }
                if (this._onCanvasBlurObserver) {
                    this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
                }
                this._onKeyboardObserver = null;
                this._onCanvasBlurObserver = null;
            }
            this._keys = [];
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
            if (this._onKeyboardObserver) {
                var camera = this.camera;
                for (var index = 0; index < this._keys.length; index++) {
                    var keyCode = this._keys[index];
                    if (this.keysLeft.indexOf(keyCode) !== -1) {
                        if (this._ctrlPressed && this.camera._useCtrlForPanning) {
                            camera.inertialPanningX -= 1 / this.panningSensibility;
                        }
                        else {
                            camera.inertialAlphaOffset -= this.angularSpeed;
                        }
                    }
                    else if (this.keysUp.indexOf(keyCode) !== -1) {
                        if (this._ctrlPressed && this.camera._useCtrlForPanning) {
                            camera.inertialPanningY += 1 / this.panningSensibility;
                        }
                        else if (this._altPressed && this.useAltToZoom) {
                            camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
                        }
                        else {
                            camera.inertialBetaOffset -= this.angularSpeed;
                        }
                    }
                    else if (this.keysRight.indexOf(keyCode) !== -1) {
                        if (this._ctrlPressed && this.camera._useCtrlForPanning) {
                            camera.inertialPanningX += 1 / this.panningSensibility;
                        }
                        else {
                            camera.inertialAlphaOffset += this.angularSpeed;
                        }
                    }
                    else if (this.keysDown.indexOf(keyCode) !== -1) {
                        if (this._ctrlPressed && this.camera._useCtrlForPanning) {
                            camera.inertialPanningY -= 1 / this.panningSensibility;
                        }
                        else if (this._altPressed && this.useAltToZoom) {
                            camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
                        }
                        else {
                            camera.inertialBetaOffset += this.angularSpeed;
                        }
                    }
                    else if (this.keysReset.indexOf(keyCode) !== -1) {
                        if (camera.useInputToRestoreState) {
                            camera.restoreState();
                        }
                    }
                }
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
            return "ArcRotateCameraKeyboardMoveInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
            return "keyboard";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
        return ArcRotateCameraKeyboardMoveInput;
    }());
    BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
    BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the mouse wheel inputs to control an arc rotate camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
        function ArcRotateCameraMouseWheelInput() {
            /**
             * Gets or Set the mouse wheel precision or how fast is the camera zooming.
             */
            this.wheelPrecision = 3.0;
            /**
             * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
             * It defines the percentage of current camera.radius to use as delta when wheel is used.
             */
            this.wheelDeltaPercentage = 0;
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            this._wheel = function (p, s) {
                //sanity check - this should be a PointerWheel event.
                if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL) {
                    return;
                }
                var event = p.event;
                var delta = 0;
                if (event.wheelDelta) {
                    if (_this.wheelDeltaPercentage) {
                        var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
                        if (event.wheelDelta > 0) {
                            delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
                        }
                        else {
                            delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
                        }
                    }
                    else {
                        delta = event.wheelDelta / (_this.wheelPrecision * 40);
                    }
                }
                else if (event.detail) {
                    delta = -event.detail / _this.wheelPrecision;
                }
                if (delta) {
                    _this.camera.inertialRadiusOffset += delta;
                }
                if (event.preventDefault) {
                    if (!noPreventDefault) {
                        event.preventDefault();
                    }
                }
            };
            this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
            if (this._observer && element) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                this._observer = null;
                this._wheel = null;
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
            return "ArcRotateCameraMouseWheelInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
            return "mousewheel";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
        return ArcRotateCameraMouseWheelInput;
    }());
    BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
    BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the pointers inputs to control an arc rotate camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var ArcRotateCameraPointersInput = /** @class */ (function () {
        function ArcRotateCameraPointersInput() {
            /**
             * Defines the buttons associated with the input to handle camera move.
             */
            this.buttons = [0, 1, 2];
            /**
             * Defines the pointer angular sensibility  along the X axis or how fast is the camera rotating.
             */
            this.angularSensibilityX = 1000.0;
            /**
             * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
             */
            this.angularSensibilityY = 1000.0;
            /**
             * Defines the pointer pinch precision or how fast is the camera zooming.
             */
            this.pinchPrecision = 12.0;
            /**
             * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
             * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
             */
            this.pinchDeltaPercentage = 0;
            /**
             * Defines the pointer panning sensibility or how fast is the camera moving.
             */
            this.panningSensibility = 1000.0;
            /**
             * Defines whether panning (2 fingers swipe) is enabled through multitouch.
             */
            this.multiTouchPanning = true;
            /**
             * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
             */
            this.multiTouchPanAndZoom = true;
            /**
             * Revers pinch action direction.
             */
            this.pinchInwards = true;
            this._isPanClick = false;
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var engine = this.camera.getEngine();
            var cacheSoloPointer; // cache pointer object for better perf on camera rotation
            var pointA = null;
            var pointB = null;
            var previousPinchSquaredDistance = 0;
            var initialDistance = 0;
            var twoFingerActivityCount = 0;
            var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
            this._pointerInput = function (p, s) {
                var evt = p.event;
                var isTouch = p.event.pointerType === "touch";
                if (engine.isInVRExclusivePointerMode) {
                    return;
                }
                if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
                    return;
                }
                var srcElement = (evt.srcElement || evt.target);
                if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
                    try {
                        srcElement.setPointerCapture(evt.pointerId);
                    }
                    catch (e) {
                        //Nothing to do with the error. Execution will continue.
                    }
                    // Manage panning with pan button click
                    _this._isPanClick = evt.button === _this.camera._panningMouseButton;
                    // manage pointers
                    cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
                    if (pointA === null) {
                        pointA = cacheSoloPointer;
                    }
                    else if (pointB === null) {
                        pointB = cacheSoloPointer;
                    }
                    if (!noPreventDefault) {
                        evt.preventDefault();
                        element.focus();
                    }
                }
                else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
                    if (_this.camera.useInputToRestoreState) {
                        _this.camera.restoreState();
                    }
                }
                else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
                    try {
                        srcElement.releasePointerCapture(evt.pointerId);
                    }
                    catch (e) {
                        //Nothing to do with the error.
                    }
                    cacheSoloPointer = null;
                    previousPinchSquaredDistance = 0;
                    previousMultiTouchPanPosition.isPaning = false;
                    previousMultiTouchPanPosition.isPinching = false;
                    twoFingerActivityCount = 0;
                    initialDistance = 0;
                    if (!isTouch) {
                        pointB = null; // Mouse and pen are mono pointer
                    }
                    //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
                    //but emptying completly pointers collection is required to fix a bug on iPhone :
                    //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
                    //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
                    if (engine._badOS) {
                        pointA = pointB = null;
                    }
                    else {
                        //only remove the impacted pointer in case of multitouch allowing on most
                        //platforms switching from rotate to zoom and pan seamlessly.
                        if (pointB && pointA && pointA.pointerId == evt.pointerId) {
                            pointA = pointB;
                            pointB = null;
                            cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
                        }
                        else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
                            pointB = null;
                            cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
                        }
                        else {
                            pointA = pointB = null;
                        }
                    }
                    if (!noPreventDefault) {
                        evt.preventDefault();
                    }
                }
                else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
                    if (!noPreventDefault) {
                        evt.preventDefault();
                    }
                    // One button down
                    if (pointA && pointB === null && cacheSoloPointer) {
                        if (_this.panningSensibility !== 0 &&
                            ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
                            _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
                            _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
                        }
                        else {
                            var offsetX = evt.clientX - cacheSoloPointer.x;
                            var offsetY = evt.clientY - cacheSoloPointer.y;
                            _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
                            _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
                        }
                        cacheSoloPointer.x = evt.clientX;
                        cacheSoloPointer.y = evt.clientY;
                    }
                    // Two buttons down: pinch/pan
                    else if (pointA && pointB) {
                        //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
                        var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
                        ed.x = evt.clientX;
                        ed.y = evt.clientY;
                        var direction = _this.pinchInwards ? 1 : -1;
                        var distX = pointA.x - pointB.x;
                        var distY = pointA.y - pointB.y;
                        var pinchSquaredDistance = (distX * distX) + (distY * distY);
                        var pinchDistance = Math.sqrt(pinchSquaredDistance);
                        if (previousPinchSquaredDistance === 0) {
                            initialDistance = pinchDistance;
                            previousPinchSquaredDistance = pinchSquaredDistance;
                            previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
                            previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
                            return;
                        }
                        if (_this.multiTouchPanAndZoom) {
                            if (_this.pinchDeltaPercentage) {
                                _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
                            }
                            else {
                                _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
                                    (_this.pinchPrecision *
                                        ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
                                        direction);
                            }
                            if (_this.panningSensibility !== 0) {
                                var pointersCenterX = (pointA.x + pointB.x) / 2;
                                var pointersCenterY = (pointA.y + pointB.y) / 2;
                                var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
                                var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
                                previousMultiTouchPanPosition.x = pointersCenterX;
                                previousMultiTouchPanPosition.y = pointersCenterY;
                                _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
                                _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
                            }
                        }
                        else {
                            twoFingerActivityCount++;
                            if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
                                if (_this.pinchDeltaPercentage) {
                                    _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
                                }
                                else {
                                    _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
                                        (_this.pinchPrecision *
                                            ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
                                            direction);
                                }
                                previousMultiTouchPanPosition.isPaning = false;
                                previousMultiTouchPanPosition.isPinching = true;
                            }
                            else {
                                if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
                                    if (!previousMultiTouchPanPosition.isPaning) {
                                        previousMultiTouchPanPosition.isPaning = true;
                                        previousMultiTouchPanPosition.isPinching = false;
                                        previousMultiTouchPanPosition.x = ed.x;
                                        previousMultiTouchPanPosition.y = ed.y;
                                        return;
                                    }
                                    _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
                                    _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
                                }
                            }
                            if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
                                previousMultiTouchPanPosition.x = ed.x;
                                previousMultiTouchPanPosition.y = ed.y;
                            }
                        }
                        previousPinchSquaredDistance = pinchSquaredDistance;
                    }
                }
            };
            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
            this._onContextMenu = function (evt) {
                evt.preventDefault();
            };
            if (!this.camera._useCtrlForPanning) {
                element.addEventListener("contextmenu", this._onContextMenu, false);
            }
            this._onLostFocus = function () {
                //this._keys = [];
                pointA = pointB = null;
                previousPinchSquaredDistance = 0;
                previousMultiTouchPanPosition.isPaning = false;
                previousMultiTouchPanPosition.isPinching = false;
                twoFingerActivityCount = 0;
                cacheSoloPointer = null;
                initialDistance = 0;
            };
            this._onMouseMove = function (evt) {
                if (!engine.isPointerLock) {
                    return;
                }
                var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
                var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
                _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
                _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
                if (!noPreventDefault) {
                    evt.preventDefault();
                }
            };
            this._onGestureStart = function (e) {
                if (window.MSGesture === undefined) {
                    return;
                }
                if (!_this._MSGestureHandler) {
                    _this._MSGestureHandler = new MSGesture();
                    _this._MSGestureHandler.target = element;
                }
                _this._MSGestureHandler.addPointer(e.pointerId);
            };
            this._onGesture = function (e) {
                _this.camera.radius *= e.scale;
                if (e.preventDefault) {
                    if (!noPreventDefault) {
                        e.stopPropagation();
                        e.preventDefault();
                    }
                }
            };
            element.addEventListener("mousemove", this._onMouseMove, false);
            element.addEventListener("MSPointerDown", this._onGestureStart, false);
            element.addEventListener("MSGestureChange", this._onGesture, false);
            BABYLON.Tools.RegisterTopRootEvents([
                { name: "blur", handler: this._onLostFocus }
            ]);
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
            if (this._onLostFocus) {
                BABYLON.Tools.UnregisterTopRootEvents([
                    { name: "blur", handler: this._onLostFocus }
                ]);
            }
            if (element && this._observer) {
                this.camera.getScene().onPointerObservable.remove(this._observer);
                this._observer = null;
                if (this._onContextMenu) {
                    element.removeEventListener("contextmenu", this._onContextMenu);
                }
                if (this._onMouseMove) {
                    element.removeEventListener("mousemove", this._onMouseMove);
                }
                if (this._onGestureStart) {
                    element.removeEventListener("MSPointerDown", this._onGestureStart);
                }
                if (this._onGesture) {
                    element.removeEventListener("MSGestureChange", this._onGesture);
                }
                this._isPanClick = false;
                this.pinchInwards = true;
                this._onMouseMove = null;
                this._onGestureStart = null;
                this._onGesture = null;
                this._MSGestureHandler = null;
                this._onLostFocus = null;
                this._onContextMenu = null;
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        ArcRotateCameraPointersInput.prototype.getClassName = function () {
            return "ArcRotateCameraPointersInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
            return "pointers";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
        return ArcRotateCameraPointersInput;
    }());
    BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
    BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Default Inputs manager for the ArcRotateCamera.
     * It groups all the default supported inputs for ease of use.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
        __extends(ArcRotateCameraInputsManager, _super);
        /**
         * Instantiates a new ArcRotateCameraInputsManager.
         * @param camera Defines the camera the inputs belong to
         */
        function ArcRotateCameraInputsManager(camera) {
            return _super.call(this, camera) || this;
        }
        /**
         * Add mouse wheel input support to the input manager.
         * @returns the current input manager
         */
        ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
            this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
            return this;
        };
        /**
         * Add pointers input support to the input manager.
         * @returns the current input manager
         */
        ArcRotateCameraInputsManager.prototype.addPointers = function () {
            this.add(new BABYLON.ArcRotateCameraPointersInput());
            return this;
        };
        /**
         * Add keyboard input support to the input manager.
         * @returns the current input manager
         */
        ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
            this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
            return this;
        };
        /**
         * Add orientation input support to the input manager.
         * @returns the current input manager
         */
        ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
            this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
            return this;
        };
        return ArcRotateCameraInputsManager;
    }(BABYLON.CameraInputsManager));
    BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
        return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * This represents an orbital type of camera.
     *
     * This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
     * Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
     * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
     */
    var ArcRotateCamera = /** @class */ (function (_super) {
        __extends(ArcRotateCamera, _super);
        /**
         * Instantiates a new ArcRotateCamera in a given scene
         * @param name Defines the name of the camera
         * @param alpha Defines the camera rotation along the logitudinal axis
         * @param beta Defines the camera rotation along the latitudinal axis
         * @param radius Defines the camera distance from its target
         * @param target Defines the camera target
         * @param scene Defines the scene the camera belongs to
         * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
         */
        function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
            if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
            var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
            /**
             * Current inertia value on the longitudinal axis.
             * The bigger this number the longer it will take for the camera to stop.
             */
            _this.inertialAlphaOffset = 0;
            /**
             * Current inertia value on the latitudinal axis.
             * The bigger this number the longer it will take for the camera to stop.
             */
            _this.inertialBetaOffset = 0;
            /**
             * Current inertia value on the radius axis.
             * The bigger this number the longer it will take for the camera to stop.
             */
            _this.inertialRadiusOffset = 0;
            /**
             * Minimum allowed angle on the longitudinal axis.
             * This can help limiting how the Camera is able to move in the scene.
             */
            _this.lowerAlphaLimit = null;
            /**
             * Maximum allowed angle on the longitudinal axis.
             * This can help limiting how the Camera is able to move in the scene.
             */
            _this.upperAlphaLimit = null;
            /**
             * Minimum allowed angle on the latitudinal axis.
             * This can help limiting how the Camera is able to move in the scene.
             */
            _this.lowerBetaLimit = 0.01;
            /**
             * Maximum allowed angle on the latitudinal axis.
             * This can help limiting how the Camera is able to move in the scene.
             */
            _this.upperBetaLimit = Math.PI;
            /**
             * Minimum allowed distance of the camera to the target (The camera can not get closer).
             * This can help limiting how the Camera is able to move in the scene.
             */
            _this.lowerRadiusLimit = null;
            /**
             * Maximum allowed distance of the camera to the target (The camera can not get further).
             * This can help limiting how the Camera is able to move in the scene.
             */
            _this.upperRadiusLimit = null;
            /**
             * Defines the current inertia value used during panning of the camera along the X axis.
             */
            _this.inertialPanningX = 0;
            /**
             * Defines the current inertia value used during panning of the camera along the Y axis.
             */
            _this.inertialPanningY = 0;
            /**
             * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
             * Basically if your fingers moves away from more than this distance you will be considered
             * in pinch mode.
             */
            _this.pinchToPanMaxDistance = 20;
            /**
             * Defines the maximum distance the camera can pan.
             * This could help keeping the cammera always in your scene.
             */
            _this.panningDistanceLimit = null;
            /**
             * Defines the target of the camera before paning.
             */
            _this.panningOriginTarget = BABYLON.Vector3.Zero();
            /**
             * Defines the value of the inertia used during panning.
             * 0 would mean stop inertia and one would mean no decelleration at all.
             */
            _this.panningInertia = 0.9;
            //-- end properties for backward compatibility for inputs
            /**
             * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
             */
            _this.zoomOnFactor = 1;
            /**
             * Defines a screen offset for the camera position.
             */
            _this.targetScreenOffset = BABYLON.Vector2.Zero();
            /**
             * Allows the camera to be completely reversed.
             * If false the camera can not arrive upside down.
             */
            _this.allowUpsideDown = true;
            /**
             * Define if double tap/click is used to restore the previously saved state of the camera.
             */
            _this.useInputToRestoreState = true;
            /** @hidden */
            _this._viewMatrix = new BABYLON.Matrix();
            /**
             * Defines the allowed panning axis.
             */
            _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
            /**
             * Observable triggered when the mesh target has been changed on the camera.
             */
            _this.onMeshTargetChangedObservable = new BABYLON.Observable();
            /**
             * Defines whether the camera should check collision with the objects oh the scene.
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
             */
            _this.checkCollisions = false;
            /**
             * Defines the collision radius of the camera.
             * This simulates a sphere around the camera.
             * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
             */
            _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
            _this._previousPosition = BABYLON.Vector3.Zero();
            _this._collisionVelocity = BABYLON.Vector3.Zero();
            _this._newPosition = BABYLON.Vector3.Zero();
            _this._computationVector = BABYLON.Vector3.Zero();
            _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
                if (collidedMesh === void 0) { collidedMesh = null; }
                if (_this.getScene().workerCollisions && _this.checkCollisions) {
                    newPosition.multiplyInPlace(_this._collider._radius);
                }
                if (!collidedMesh) {
                    _this._previousPosition.copyFrom(_this.position);
                }
                else {
                    _this.setPosition(newPosition);
                    if (_this.onCollide) {
                        _this.onCollide(collidedMesh);
                    }
                }
                // Recompute because of constraints
                var cosa = Math.cos(_this.alpha);
                var sina = Math.sin(_this.alpha);
                var cosb = Math.cos(_this.beta);
                var sinb = Math.sin(_this.beta);
                if (sinb === 0) {
                    sinb = 0.0001;
                }
                var target = _this._getTargetPosition();
                _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
                target.addToRef(_this._computationVector, _this._newPosition);
                _this.position.copyFrom(_this._newPosition);
                var up = _this.upVector;
                if (_this.allowUpsideDown && _this.beta < 0) {
                    up = up.clone();
                    up = up.negate();
                }
                _this._computeViewMatrix(_this.position, target, up);
                _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
                _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
                _this._collisionTriggered = false;
            };
            _this._target = BABYLON.Vector3.Zero();
            if (target) {
                _this.setTarget(target);
            }
            _this.alpha = alpha;
            _this.beta = beta;
            _this.radius = radius;
            _this.getViewMatrix();
            _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
            _this.inputs.addKeyboard().addMouseWheel().addPointers();
            return _this;
        }
        Object.defineProperty(ArcRotateCamera.prototype, "target", {
            /**
             * Defines the target point of the camera.
             * The camera looks towards it form the radius distance.
             */
            get: function () {
                return this._target;
            },
            set: function (value) {
                this.setTarget(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
            //-- begin properties for backward compatibility for inputs
            /**
             * Gets or Set the pointer angular sensibility  along the X axis or how fast is the camera rotating.
             */
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    return pointers.angularSensibilityX;
                }
                return 0;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.angularSensibilityX = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
            /**
             * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
             */
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    return pointers.angularSensibilityY;
                }
                return 0;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.angularSensibilityY = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
            /**
             * Gets or Set the pointer pinch precision or how fast is the camera zooming.
             */
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    return pointers.pinchPrecision;
                }
                return 0;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.pinchPrecision = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
            /**
             * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
             * It will be used instead of pinchDeltaPrecision if different from 0.
             * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
             */
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    return pointers.pinchDeltaPercentage;
                }
                return 0;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.pinchDeltaPercentage = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
            /**
             * Gets or Set the pointer panning sensibility or how fast is the camera moving.
             */
            get: function () {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    return pointers.panningSensibility;
                }
                return 0;
            },
            set: function (value) {
                var pointers = this.inputs.attached["pointers"];
                if (pointers) {
                    pointers.panningSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
            /**
             * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysUp;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysUp = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
            /**
             * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysDown;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysDown = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
            /**
             * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysLeft;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysLeft = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
            /**
             * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
             */
            get: function () {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    return keyboard.keysRight;
                }
                return [];
            },
            set: function (value) {
                var keyboard = this.inputs.attached["keyboard"];
                if (keyboard) {
                    keyboard.keysRight = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
            /**
             * Gets or Set the mouse wheel precision or how fast is the camera zooming.
             */
            get: function () {
                var mousewheel = this.inputs.attached["mousewheel"];
                if (mousewheel) {
                    return mousewheel.wheelPrecision;
                }
                return 0;
            },
            set: function (value) {
                var mousewheel = this.inputs.attached["mousewheel"];
                if (mousewheel) {
                    mousewheel.wheelPrecision = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
            /**
             * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
             * It will be used instead of pinchDeltaPrecision if different from 0.
             * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
             */
            get: function () {
                var mousewheel = this.inputs.attached["mousewheel"];
                if (mousewheel) {
                    return mousewheel.wheelDeltaPercentage;
                }
                return 0;
            },
            set: function (value) {
                var mousewheel = this.inputs.attached["mousewheel"];
                if (mousewheel) {
                    mousewheel.wheelDeltaPercentage = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
            /**
             * Gets the bouncing behavior of the camera if it has been enabled.
             * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
             */
            get: function () {
                return this._bouncingBehavior;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
            /**
             * Defines if the bouncing behavior of the camera is enabled on the camera.
             * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
             */
            get: function () {
                return this._bouncingBehavior != null;
            },
            set: function (value) {
                if (value === this.useBouncingBehavior) {
                    return;
                }
                if (value) {
                    this._bouncingBehavior = new BABYLON.BouncingBehavior();
                    this.addBehavior(this._bouncingBehavior);
                }
                else if (this._bouncingBehavior) {
                    this.removeBehavior(this._bouncingBehavior);
                    this._bouncingBehavior = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
            /**
             * Gets the framing behavior of the camera if it has been enabled.
             * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
             */
            get: function () {
                return this._framingBehavior;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
            /**
             * Defines if the framing behavior of the camera is enabled on the camera.
             * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
             */
            get: function () {
                return this._framingBehavior != null;
            },
            set: function (value) {
                if (value === this.useFramingBehavior) {
                    return;
                }
                if (value) {
                    this._framingBehavior = new BABYLON.FramingBehavior();
                    this.addBehavior(this._framingBehavior);
                }
                else if (this._framingBehavior) {
                    this.removeBehavior(this._framingBehavior);
                    this._framingBehavior = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
            /**
             * Gets the auto rotation behavior of the camera if it has been enabled.
             * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
             */
            get: function () {
                return this._autoRotationBehavior;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
            /**
             * Defines if the auto rotation behavior of the camera is enabled on the camera.
             * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
             */
            get: function () {
                return this._autoRotationBehavior != null;
            },
            set: function (value) {
                if (value === this.useAutoRotationBehavior) {
                    return;
                }
                if (value) {
                    this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
                    this.addBehavior(this._autoRotationBehavior);
                }
                else if (this._autoRotationBehavior) {
                    this.removeBehavior(this._autoRotationBehavior);
                    this._autoRotationBehavior = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        // Cache
        /** @hidden */
        ArcRotateCamera.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cache.alpha = undefined;
            this._cache.beta = undefined;
            this._cache.radius = undefined;
            this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
        };
        /** @hidden */
        ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            this._cache._target.copyFrom(this._getTargetPosition());
            this._cache.alpha = this.alpha;
            this._cache.beta = this.beta;
            this._cache.radius = this.radius;
            this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
        };
        ArcRotateCamera.prototype._getTargetPosition = function () {
            if (this._targetHost && this._targetHost.getAbsolutePosition) {
                var pos = this._targetHost.getAbsolutePosition();
                if (this._targetBoundingCenter) {
                    pos.addToRef(this._targetBoundingCenter, this._target);
                }
                else {
                    this._target.copyFrom(pos);
                }
            }
            var lockedTargetPosition = this._getLockedTargetPosition();
            if (lockedTargetPosition) {
                return lockedTargetPosition;
            }
            return this._target;
        };
        /**
         * Stores the current state of the camera (alpha, beta, radius and target)
         * @returns the camera itself
         */
        ArcRotateCamera.prototype.storeState = function () {
            this._storedAlpha = this.alpha;
            this._storedBeta = this.beta;
            this._storedRadius = this.radius;
            this._storedTarget = this._getTargetPosition().clone();
            return _super.prototype.storeState.call(this);
        };
        /**
         * @hidden
         * Restored camera state. You must call storeState() first
         */
        ArcRotateCamera.prototype._restoreStateValues = function () {
            if (!_super.prototype._restoreStateValues.call(this)) {
                return false;
            }
            this.alpha = this._storedAlpha;
            this.beta = this._storedBeta;
            this.radius = this._storedRadius;
            this.setTarget(this._storedTarget.clone());
            this.inertialAlphaOffset = 0;
            this.inertialBetaOffset = 0;
            this.inertialRadiusOffset = 0;
            this.inertialPanningX = 0;
            this.inertialPanningY = 0;
            return true;
        };
        // Synchronized
        /** @hidden */
        ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
            if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
                return false;
            }
            return this._cache._target.equals(this._getTargetPosition())
                && this._cache.alpha === this.alpha
                && this._cache.beta === this.beta
                && this._cache.radius === this.radius
                && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
        };
        /**
         * Attached controls to the current camera.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         * @param useCtrlForPanning  Defines whether ctrl is used for paning within the controls
         * @param panningMouseButton Defines whether panning is allowed through mouse click button
         */
        ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
            var _this = this;
            if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
            if (panningMouseButton === void 0) { panningMouseButton = 2; }
            this._useCtrlForPanning = useCtrlForPanning;
            this._panningMouseButton = panningMouseButton;
            this.inputs.attachElement(element, noPreventDefault);
            this._reset = function () {
                _this.inertialAlphaOffset = 0;
                _this.inertialBetaOffset = 0;
                _this.inertialRadiusOffset = 0;
                _this.inertialPanningX = 0;
                _this.inertialPanningY = 0;
            };
        };
        /**
         * Detach the current controls from the camera.
         * The camera will stop reacting to inputs.
         * @param element Defines the element to stop listening the inputs from
         */
        ArcRotateCamera.prototype.detachControl = function (element) {
            this.inputs.detachElement(element);
            if (this._reset) {
                this._reset();
            }
        };
        /** @hidden */
        ArcRotateCamera.prototype._checkInputs = function () {
            //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
            if (this._collisionTriggered) {
                return;
            }
            this.inputs.checkInputs();
            // Inertia
            if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
                var inertialAlphaOffset = this.inertialAlphaOffset;
                if (this.beta <= 0) {
                    inertialAlphaOffset *= -1;
                }
                if (this.getScene().useRightHandedSystem) {
                    inertialAlphaOffset *= -1;
                }
                if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
                    inertialAlphaOffset *= -1;
                }
                this.alpha += inertialAlphaOffset;
                this.beta += this.inertialBetaOffset;
                this.radius -= this.inertialRadiusOffset;
                this.inertialAlphaOffset *= this.inertia;
                this.inertialBetaOffset *= this.inertia;
                this.inertialRadiusOffset *= this.inertia;
                if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon) {
                    this.inertialAlphaOffset = 0;
                }
                if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon) {
                    this.inertialBetaOffset = 0;
                }
                if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon) {
                    this.inertialRadiusOffset = 0;
                }
            }
            // Panning inertia
            if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
                if (!this._localDirection) {
                    this._localDirection = BABYLON.Vector3.Zero();
                    this._transformedDirection = BABYLON.Vector3.Zero();
                }
                this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
                this._localDirection.multiplyInPlace(this.panningAxis);
                this._viewMatrix.invertToRef(this._cameraTransformMatrix);
                BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
                //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
                if (!this.panningAxis.y) {
                    this._transformedDirection.y = 0;
                }
                if (!this._targetHost) {
                    if (this.panningDistanceLimit) {
                        this._transformedDirection.addInPlace(this._target);
                        var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
                        if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
                            this._target.copyFrom(this._transformedDirection);
                        }
                    }
                    else {
                        this._target.addInPlace(this._transformedDirection);
                    }
                }
                this.inertialPanningX *= this.panningInertia;
                this.inertialPanningY *= this.panningInertia;
                if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon) {
                    this.inertialPanningX = 0;
                }
                if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon) {
                    this.inertialPanningY = 0;
                }
            }
            // Limits
            this._checkLimits();
            _super.prototype._checkInputs.call(this);
        };
        ArcRotateCamera.prototype._checkLimits = function () {
            if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
                if (this.allowUpsideDown && this.beta > Math.PI) {
                    this.beta = this.beta - (2 * Math.PI);
                }
            }
            else {
                if (this.beta < this.lowerBetaLimit) {
                    this.beta = this.lowerBetaLimit;
                }
            }
            if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
                if (this.allowUpsideDown && this.beta < -Math.PI) {
                    this.beta = this.beta + (2 * Math.PI);
                }
            }
            else {
                if (this.beta > this.upperBetaLimit) {
                    this.beta = this.upperBetaLimit;
                }
            }
            if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
                this.alpha = this.lowerAlphaLimit;
            }
            if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
                this.alpha = this.upperAlphaLimit;
            }
            if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
                this.radius = this.lowerRadiusLimit;
            }
            if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
                this.radius = this.upperRadiusLimit;
            }
        };
        /**
         * Rebuilds angles (alpha, beta) and radius from the give position and target.
         */
        ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
            this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
            this.radius = this._computationVector.length();
            if (this.radius === 0) {
                this.radius = 0.0001; // Just to avoid division by zero
            }
            // Alpha
            this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
            if (this._computationVector.z < 0) {
                this.alpha = 2 * Math.PI - this.alpha;
            }
            // Beta
            this.beta = Math.acos(this._computationVector.y / this.radius);
            this._checkLimits();
        };
        /**
         * Use a position to define the current camera related information like aplha, beta and radius
         * @param position Defines the position to set the camera at
         */
        ArcRotateCamera.prototype.setPosition = function (position) {
            if (this.position.equals(position)) {
                return;
            }
            this.position.copyFrom(position);
            this.rebuildAnglesAndRadius();
        };
        /**
         * Defines the target the camera should look at.
         * This will automatically adapt alpha beta and radius to fit within the new target.
         * @param target Defines the new target as a Vector or a mesh
         * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
         * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
         */
        ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
            if (toBoundingCenter === void 0) { toBoundingCenter = false; }
            if (allowSamePosition === void 0) { allowSamePosition = false; }
            if (target.getBoundingInfo) {
                if (toBoundingCenter) {
                    this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
                }
                else {
                    this._targetBoundingCenter = null;
                }
                this._targetHost = target;
                this._target = this._getTargetPosition();
                this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
            }
            else {
                var newTarget = target;
                var currentTarget = this._getTargetPosition();
                if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
                    return;
                }
                this._targetHost = null;
                this._target = newTarget;
                this._targetBoundingCenter = null;
                this.onMeshTargetChangedObservable.notifyObservers(null);
            }
            this.rebuildAnglesAndRadius();
        };
        /** @hidden */
        ArcRotateCamera.prototype._getViewMatrix = function () {
            // Compute
            var cosa = Math.cos(this.alpha);
            var sina = Math.sin(this.alpha);
            var cosb = Math.cos(this.beta);
            var sinb = Math.sin(this.beta);
            if (sinb === 0) {
                sinb = 0.0001;
            }
            var target = this._getTargetPosition();
            this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
            target.addToRef(this._computationVector, this._newPosition);
            if (this.getScene().collisionsEnabled && this.checkCollisions) {
                if (!this._collider) {
                    this._collider = new BABYLON.Collider();
                }
                this._collider._radius = this.collisionRadius;
                this._newPosition.subtractToRef(this.position, this._collisionVelocity);
                this._collisionTriggered = true;
                this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
            }
            else {
                this.position.copyFrom(this._newPosition);
                var up = this.upVector;
                if (this.allowUpsideDown && sinb < 0) {
                    up = up.clone();
                    up = up.negate();
                }
                this._computeViewMatrix(this.position, target, up);
                this._viewMatrix.m[12] += this.targetScreenOffset.x;
                this._viewMatrix.m[13] += this.targetScreenOffset.y;
            }
            this._currentTarget = target;
            return this._viewMatrix;
        };
        /**
         * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
         * @param meshes Defines the mesh to zoom on
         * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
         */
        ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
            if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
            meshes = meshes || this.getScene().meshes;
            var minMaxVector = BABYLON.Mesh.MinMax(meshes);
            var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
            this.radius = distance * this.zoomOnFactor;
            this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
        };
        /**
         * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
         * The target will be changed but the radius
         * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
         * @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
         */
        ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
            if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
            var meshesOrMinMaxVector;
            var distance;
            if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
                var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
                meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
                distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
            }
            else { //minMaxVector and distance
                var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
                meshesOrMinMaxVector = minMaxVectorAndDistance;
                distance = minMaxVectorAndDistance.distance;
            }
            this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
            if (!doNotUpdateMaxZ) {
                this.maxZ = distance * 2;
            }
        };
        /**
         * @override
         * Override Camera.createRigCamera
         */
        ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
            var alphaShift = 0;
            switch (this.cameraRigMode) {
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                case BABYLON.Camera.RIG_MODE_VR:
                    alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
                    break;
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                    alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
                    break;
            }
            var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
            rigCam._cameraRigParams = {};
            return rigCam;
        };
        /**
         * @hidden
         * @override
         * Override Camera._updateRigCameras
         */
        ArcRotateCamera.prototype._updateRigCameras = function () {
            var camLeft = this._rigCameras[0];
            var camRight = this._rigCameras[1];
            camLeft.beta = camRight.beta = this.beta;
            camLeft.radius = camRight.radius = this.radius;
            switch (this.cameraRigMode) {
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
                case BABYLON.Camera.RIG_MODE_VR:
                    camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
                    camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
                    break;
                case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
                    camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
                    camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
                    break;
            }
            _super.prototype._updateRigCameras.call(this);
        };
        /**
         * Destroy the camera and release the current resources hold by it.
         */
        ArcRotateCamera.prototype.dispose = function () {
            this.inputs.clear();
            _super.prototype.dispose.call(this);
        };
        /**
         * Gets the current object class name.
         * @return the class name
         */
        ArcRotateCamera.prototype.getClassName = function () {
            return "ArcRotateCamera";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "alpha", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "beta", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "radius", void 0);
        __decorate([
            BABYLON.serializeAsVector3("target")
        ], ArcRotateCamera.prototype, "_target", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "panningInertia", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
        return ArcRotateCamera;
    }(BABYLON.TargetCamera));
    BABYLON.ArcRotateCamera = ArcRotateCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCamera.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
        return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * The HemisphericLight simulates the ambient environment light,
     * so the passed direction is the light reflection direction, not the incoming direction.
     */
    var HemisphericLight = /** @class */ (function (_super) {
        __extends(HemisphericLight, _super);
        /**
         * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
         * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
         * The HemisphericLight can't cast shadows.
         * Documentation : http://doc.babylonjs.com/tutorials/lights
         * @param name The friendly name of the light
         * @param direction The direction of the light reflection
         * @param scene The scene the light belongs to
         */
        function HemisphericLight(name, direction, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * The groundColor is the light in the opposite direction to the one specified during creation.
             * You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
             */
            _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
            _this.direction = direction || BABYLON.Vector3.Up();
            return _this;
        }
        HemisphericLight.prototype._buildUniformLayout = function () {
            this._uniformBuffer.addUniform("vLightData", 4);
            this._uniformBuffer.addUniform("vLightDiffuse", 4);
            this._uniformBuffer.addUniform("vLightSpecular", 3);
            this._uniformBuffer.addUniform("vLightGround", 3);
            this._uniformBuffer.addUniform("shadowsInfo", 3);
            this._uniformBuffer.addUniform("depthValues", 2);
            this._uniformBuffer.create();
        };
        /**
         * Returns the string "HemisphericLight".
         * @return The class name
         */
        HemisphericLight.prototype.getClassName = function () {
            return "HemisphericLight";
        };
        /**
         * Sets the HemisphericLight direction towards the passed target (Vector3).
         * Returns the updated direction.
         * @param target The target the direction should point to
         * @return The computed direction
         */
        HemisphericLight.prototype.setDirectionToTarget = function (target) {
            this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
            return this.direction;
        };
        /**
         * Returns the shadow generator associated to the light.
         * @returns Always null for hemispheric lights because it does not support shadows.
         */
        HemisphericLight.prototype.getShadowGenerator = function () {
            return null;
        };
        /**
         * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
         * @param effect The effect to update
         * @param lightIndex The index of the light in the effect to update
         * @returns The hemispheric light
         */
        HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
            var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
            this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
            this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
            return this;
        };
        /**
         * Computes the world matrix of the node
         * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
         * @param useWasUpdatedFlag defines a reserved property
         * @returns the world matrix
         */
        HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            return this._worldMatrix;
        };
        /**
         * Returns the integer 3.
         * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
         */
        HemisphericLight.prototype.getTypeID = function () {
            return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
        };
        /**
         * Prepares the list of defines specific to the light type.
         * @param defines the list of defines
         * @param lightIndex defines the index of the light for the effect
         */
        HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
            defines["HEMILIGHT" + lightIndex] = true;
        };
        __decorate([
            BABYLON.serializeAsColor3()
        ], HemisphericLight.prototype, "groundColor", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], HemisphericLight.prototype, "direction", void 0);
        return HemisphericLight;
    }(BABYLON.Light));
    BABYLON.HemisphericLight = HemisphericLight;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.hemisphericLight.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Base implementation IShadowLight
     * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
     */
    var ShadowLight = /** @class */ (function (_super) {
        __extends(ShadowLight, _super);
        function ShadowLight() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._needProjectionMatrixCompute = true;
            return _this;
        }
        ShadowLight.prototype._setPosition = function (value) {
            this._position = value;
        };
        Object.defineProperty(ShadowLight.prototype, "position", {
            /**
             * Sets the position the shadow will be casted from. Also use as the light position for both
             * point and spot lights.
             */
            get: function () {
                return this._position;
            },
            /**
             * Sets the position the shadow will be casted from. Also use as the light position for both
             * point and spot lights.
             */
            set: function (value) {
                this._setPosition(value);
            },
            enumerable: true,
            configurable: true
        });
        ShadowLight.prototype._setDirection = function (value) {
            this._direction = value;
        };
        Object.defineProperty(ShadowLight.prototype, "direction", {
            /**
             * In 2d mode (needCube being false), gets the direction used to cast the shadow.
             * Also use as the light direction on spot and directional lights.
             */
            get: function () {
                return this._direction;
            },
            /**
             * In 2d mode (needCube being false), sets the direction used to cast the shadow.
             * Also use as the light direction on spot and directional lights.
             */
            set: function (value) {
                this._setDirection(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
            /**
             * Gets the shadow projection clipping minimum z value.
             */
            get: function () {
                return this._shadowMinZ;
            },
            /**
             * Sets the shadow projection clipping minimum z value.
             */
            set: function (value) {
                this._shadowMinZ = value;
                this.forceProjectionMatrixCompute();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
            /**
             * Sets the shadow projection clipping maximum z value.
             */
            get: function () {
                return this._shadowMaxZ;
            },
            /**
             * Gets the shadow projection clipping maximum z value.
             */
            set: function (value) {
                this._shadowMaxZ = value;
                this.forceProjectionMatrixCompute();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
         * @returns true if the information has been computed, false if it does not need to (no parenting)
         */
        ShadowLight.prototype.computeTransformedInformation = function () {
            if (this.parent && this.parent.getWorldMatrix) {
                if (!this.transformedPosition) {
                    this.transformedPosition = BABYLON.Vector3.Zero();
                }
                BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
                // In case the direction is present.
                if (this.direction) {
                    if (!this.transformedDirection) {
                        this.transformedDirection = BABYLON.Vector3.Zero();
                    }
                    BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
                }
                return true;
            }
            return false;
        };
        /**
         * Return the depth scale used for the shadow map.
         * @returns the depth scale.
         */
        ShadowLight.prototype.getDepthScale = function () {
            return 50.0;
        };
        /**
         * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
         * @param faceIndex The index of the face we are computed the direction to generate shadow
         * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
         */
        ShadowLight.prototype.getShadowDirection = function (faceIndex) {
            return this.transformedDirection ? this.transformedDirection : this.direction;
        };
        /**
         * Returns the ShadowLight absolute position in the World.
         * @returns the position vector in world space
         */
        ShadowLight.prototype.getAbsolutePosition = function () {
            return this.transformedPosition ? this.transformedPosition : this.position;
        };
        /**
         * Sets the ShadowLight direction toward the passed target.
         * @param target The point tot target in local space
         * @returns the updated ShadowLight direction
         */
        ShadowLight.prototype.setDirectionToTarget = function (target) {
            this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
            return this.direction;
        };
        /**
         * Returns the light rotation in euler definition.
         * @returns the x y z rotation in local space.
         */
        ShadowLight.prototype.getRotation = function () {
            this.direction.normalize();
            var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
            var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
            return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
        };
        /**
         * Returns whether or not the shadow generation require a cube texture or a 2d texture.
         * @returns true if a cube texture needs to be use
         */
        ShadowLight.prototype.needCube = function () {
            return false;
        };
        /**
         * Detects if the projection matrix requires to be recomputed this frame.
         * @returns true if it requires to be recomputed otherwise, false.
         */
        ShadowLight.prototype.needProjectionMatrixCompute = function () {
            return this._needProjectionMatrixCompute;
        };
        /**
         * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
         */
        ShadowLight.prototype.forceProjectionMatrixCompute = function () {
            this._needProjectionMatrixCompute = true;
        };
        /** @hidden */
        ShadowLight.prototype._initCache = function () {
            _super.prototype._initCache.call(this);
            this._cache.position = BABYLON.Vector3.Zero();
        };
        /** @hidden */
        ShadowLight.prototype._isSynchronized = function () {
            if (!this._cache.position.equals(this.position)) {
                return false;
            }
            return true;
        };
        /**
         * Computes the world matrix of the node
         * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
         * @returns the world matrix
         */
        ShadowLight.prototype.computeWorldMatrix = function (force) {
            if (!force && this.isSynchronized()) {
                this._currentRenderId = this.getScene().getRenderId();
                return this._worldMatrix;
            }
            this._updateCache();
            this._cache.position.copyFrom(this.position);
            if (!this._worldMatrix) {
                this._worldMatrix = BABYLON.Matrix.Identity();
            }
            BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
            if (this.parent && this.parent.getWorldMatrix) {
                this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
                this._markSyncedWithParent();
            }
            // Cache the determinant
            this._worldMatrixDeterminant = this._worldMatrix.determinant();
            return this._worldMatrix;
        };
        /**
         * Gets the minZ used for shadow according to both the scene and the light.
         * @param activeCamera The camera we are returning the min for
         * @returns the depth min z
         */
        ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
            return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
        };
        /**
         * Gets the maxZ used for shadow according to both the scene and the light.
         * @param activeCamera The camera we are returning the max for
         * @returns the depth max z
         */
        ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
            return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
        };
        /**
         * Sets the shadow projection matrix in parameter to the generated projection matrix.
         * @param matrix The materix to updated with the projection information
         * @param viewMatrix The transform matrix of the light
         * @param renderList The list of mesh to render in the map
         * @returns The current light
         */
        ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            if (this.customProjectionMatrixBuilder) {
                this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
            }
            else {
                this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
            }
            return this;
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], ShadowLight.prototype, "position", null);
        __decorate([
            BABYLON.serializeAsVector3()
        ], ShadowLight.prototype, "direction", null);
        __decorate([
            BABYLON.serialize()
        ], ShadowLight.prototype, "shadowMinZ", null);
        __decorate([
            BABYLON.serialize()
        ], ShadowLight.prototype, "shadowMaxZ", null);
        return ShadowLight;
    }(BABYLON.Light));
    BABYLON.ShadowLight = ShadowLight;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.shadowLight.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
        return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * A point light is a light defined by an unique point in world space.
     * The light is emitted in every direction from this point.
     * A good example of a point light is a standard light bulb.
     * Documentation: https://doc.babylonjs.com/babylon101/lights
     */
    var PointLight = /** @class */ (function (_super) {
        __extends(PointLight, _super);
        /**
         * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
         * A PointLight emits the light in every direction.
         * It can cast shadows.
         * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
         * ```javascript
         * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
         * ```
         * Documentation : http://doc.babylonjs.com/tutorials/lights
         * @param name The light friendly name
         * @param position The position of the point light in the scene
         * @param scene The scene the lights belongs to
         */
        function PointLight(name, position, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._shadowAngle = Math.PI / 2;
            _this.position = position;
            return _this;
        }
        Object.defineProperty(PointLight.prototype, "shadowAngle", {
            /**
             * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
             * This specifies what angle the shadow will use to be created.
             *
             * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
             */
            get: function () {
                return this._shadowAngle;
            },
            /**
             * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
             * This specifies what angle the shadow will use to be created.
             *
             * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
             */
            set: function (value) {
                this._shadowAngle = value;
                this.forceProjectionMatrixCompute();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PointLight.prototype, "direction", {
            /**
             * Gets the direction if it has been set.
             * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
             */
            get: function () {
                return this._direction;
            },
            /**
             * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
             */
            set: function (value) {
                var previousNeedCube = this.needCube();
                this._direction = value;
                if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
                    this._shadowGenerator.recreateShadowMap();
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "PointLight"
         * @returns the class name
         */
        PointLight.prototype.getClassName = function () {
            return "PointLight";
        };
        /**
         * Returns the integer 0.
         * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
         */
        PointLight.prototype.getTypeID = function () {
            return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
        };
        /**
         * Specifies wether or not the shadowmap should be a cube texture.
         * @returns true if the shadowmap needs to be a cube texture.
         */
        PointLight.prototype.needCube = function () {
            return !this.direction;
        };
        /**
         * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
         * @param faceIndex The index of the face we are computed the direction to generate shadow
         * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
         */
        PointLight.prototype.getShadowDirection = function (faceIndex) {
            if (this.direction) {
                return _super.prototype.getShadowDirection.call(this, faceIndex);
            }
            else {
                switch (faceIndex) {
                    case 0:
                        return new BABYLON.Vector3(1.0, 0.0, 0.0);
                    case 1:
                        return new BABYLON.Vector3(-1.0, 0.0, 0.0);
                    case 2:
                        return new BABYLON.Vector3(0.0, -1.0, 0.0);
                    case 3:
                        return new BABYLON.Vector3(0.0, 1.0, 0.0);
                    case 4:
                        return new BABYLON.Vector3(0.0, 0.0, 1.0);
                    case 5:
                        return new BABYLON.Vector3(0.0, 0.0, -1.0);
                }
            }
            return BABYLON.Vector3.Zero();
        };
        /**
         * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
         * - fov = PI / 2
         * - aspect ratio : 1.0
         * - z-near and far equal to the active camera minZ and maxZ.
         * Returns the PointLight.
         */
        PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            var activeCamera = this.getScene().activeCamera;
            if (!activeCamera) {
                return;
            }
            BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
        };
        PointLight.prototype._buildUniformLayout = function () {
            this._uniformBuffer.addUniform("vLightData", 4);
            this._uniformBuffer.addUniform("vLightDiffuse", 4);
            this._uniformBuffer.addUniform("vLightSpecular", 3);
            this._uniformBuffer.addUniform("vLightFalloff", 4);
            this._uniformBuffer.addUniform("shadowsInfo", 3);
            this._uniformBuffer.addUniform("depthValues", 2);
            this._uniformBuffer.create();
        };
        /**
         * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
         * @param effect The effect to update
         * @param lightIndex The index of the light in the effect to update
         * @returns The point light
         */
        PointLight.prototype.transferToEffect = function (effect, lightIndex) {
            if (this.computeTransformedInformation()) {
                this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
            }
            else {
                this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
            }
            this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
            return this;
        };
        /**
         * Prepares the list of defines specific to the light type.
         * @param defines the list of defines
         * @param lightIndex defines the index of the light for the effect
         */
        PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
            defines["POINTLIGHT" + lightIndex] = true;
        };
        __decorate([
            BABYLON.serialize()
        ], PointLight.prototype, "shadowAngle", null);
        return PointLight;
    }(BABYLON.ShadowLight));
    BABYLON.PointLight = PointLight;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pointLight.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
        return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * A directional light is defined by a direction (what a surprise!).
     * The light is emitted from everywhere in the specified direction, and has an infinite range.
     * An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
     * Documentation: https://doc.babylonjs.com/babylon101/lights
     */
    var DirectionalLight = /** @class */ (function (_super) {
        __extends(DirectionalLight, _super);
        /**
         * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
         * The directional light is emitted from everywhere in the given direction.
         * It can cast shadows.
         * Documentation : http://doc.babylonjs.com/tutorials/lights
         * @param name The friendly name of the light
         * @param direction The direction of the light
         * @param scene The scene the light belongs to
         */
        function DirectionalLight(name, direction, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._shadowFrustumSize = 0;
            _this._shadowOrthoScale = 0.1;
            /**
             * Automatically compute the projection matrix to best fit (including all the casters)
             * on each frame.
             */
            _this.autoUpdateExtends = true;
            // Cache
            _this._orthoLeft = Number.MAX_VALUE;
            _this._orthoRight = Number.MIN_VALUE;
            _this._orthoTop = Number.MIN_VALUE;
            _this._orthoBottom = Number.MAX_VALUE;
            _this.position = direction.scale(-1.0);
            _this.direction = direction;
            return _this;
        }
        Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
            /**
             * Fix frustum size for the shadow generation. This is disabled if the value is 0.
             */
            get: function () {
                return this._shadowFrustumSize;
            },
            /**
             * Specifies a fix frustum size for the shadow generation.
             */
            set: function (value) {
                this._shadowFrustumSize = value;
                this.forceProjectionMatrixCompute();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
            /**
             * Gets the shadow projection scale against the optimal computed one.
             * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
             * This does not impact in fixed frustum size (shadowFrustumSize being set)
             */
            get: function () {
                return this._shadowOrthoScale;
            },
            /**
             * Sets the shadow projection scale against the optimal computed one.
             * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
             * This does not impact in fixed frustum size (shadowFrustumSize being set)
             */
            set: function (value) {
                this._shadowOrthoScale = value;
                this.forceProjectionMatrixCompute();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "DirectionalLight".
         * @return The class name
         */
        DirectionalLight.prototype.getClassName = function () {
            return "DirectionalLight";
        };
        /**
         * Returns the integer 1.
         * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
         */
        DirectionalLight.prototype.getTypeID = function () {
            return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
        };
        /**
         * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
         * Returns the DirectionalLight Shadow projection matrix.
         */
        DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            if (this.shadowFrustumSize > 0) {
                this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
            }
            else {
                this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
            }
        };
        /**
         * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
         * Returns the DirectionalLight Shadow projection matrix.
         */
        DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
            var activeCamera = this.getScene().activeCamera;
            if (!activeCamera) {
                return;
            }
            BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
        };
        /**
         * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
         * Returns the DirectionalLight Shadow projection matrix.
         */
        DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            var activeCamera = this.getScene().activeCamera;
            if (!activeCamera) {
                return;
            }
            // Check extends
            if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
                var tempVector3 = BABYLON.Vector3.Zero();
                this._orthoLeft = Number.MAX_VALUE;
                this._orthoRight = Number.MIN_VALUE;
                this._orthoTop = Number.MIN_VALUE;
                this._orthoBottom = Number.MAX_VALUE;
                for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
                    var mesh = renderList[meshIndex];
                    if (!mesh) {
                        continue;
                    }
                    var boundingInfo = mesh.getBoundingInfo();
                    var boundingBox = boundingInfo.boundingBox;
                    for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
                        BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
                        if (tempVector3.x < this._orthoLeft) {
                            this._orthoLeft = tempVector3.x;
                        }
                        if (tempVector3.y < this._orthoBottom) {
                            this._orthoBottom = tempVector3.y;
                        }
                        if (tempVector3.x > this._orthoRight) {
                            this._orthoRight = tempVector3.x;
                        }
                        if (tempVector3.y > this._orthoTop) {
                            this._orthoTop = tempVector3.y;
                        }
                    }
                }
            }
            var xOffset = this._orthoRight - this._orthoLeft;
            var yOffset = this._orthoTop - this._orthoBottom;
            BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
        };
        DirectionalLight.prototype._buildUniformLayout = function () {
            this._uniformBuffer.addUniform("vLightData", 4);
            this._uniformBuffer.addUniform("vLightDiffuse", 4);
            this._uniformBuffer.addUniform("vLightSpecular", 3);
            this._uniformBuffer.addUniform("shadowsInfo", 3);
            this._uniformBuffer.addUniform("depthValues", 2);
            this._uniformBuffer.create();
        };
        /**
         * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
         * @param effect The effect to update
         * @param lightIndex The index of the light in the effect to update
         * @returns The directional light
         */
        DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
            if (this.computeTransformedInformation()) {
                this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
                return this;
            }
            this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
            return this;
        };
        /**
         * Gets the minZ used for shadow according to both the scene and the light.
         *
         * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
         * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
         * @param activeCamera The camera we are returning the min for
         * @returns the depth min z
         */
        DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
            return 1;
        };
        /**
         * Gets the maxZ used for shadow according to both the scene and the light.
         *
         * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
         * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
         * @param activeCamera The camera we are returning the max for
         * @returns the depth max z
         */
        DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
            return 1;
        };
        /**
         * Prepares the list of defines specific to the light type.
         * @param defines the list of defines
         * @param lightIndex defines the index of the light for the effect
         */
        DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
            defines["DIRLIGHT" + lightIndex] = true;
        };
        __decorate([
            BABYLON.serialize()
        ], DirectionalLight.prototype, "shadowFrustumSize", null);
        __decorate([
            BABYLON.serialize()
        ], DirectionalLight.prototype, "shadowOrthoScale", null);
        __decorate([
            BABYLON.serialize()
        ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
        return DirectionalLight;
    }(BABYLON.ShadowLight));
    BABYLON.DirectionalLight = DirectionalLight;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.directionalLight.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
        return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
    });
    /**
     * A spot light is defined by a position, a direction, an angle, and an exponent.
     * These values define a cone of light starting from the position, emitting toward the direction.
     * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
     * and the exponent defines the speed of the decay of the light with distance (reach).
     * Documentation: https://doc.babylonjs.com/babylon101/lights
     */
    var SpotLight = /** @class */ (function (_super) {
        __extends(SpotLight, _super);
        /**
         * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
         * It can cast shadows.
         * Documentation : http://doc.babylonjs.com/tutorials/lights
         * @param name The light friendly name
         * @param position The position of the spot light in the scene
         * @param direction The direction of the light in the scene
         * @param angle The cone angle of the light in Radians
         * @param exponent The light decay speed with the distance from the emission spot
         * @param scene The scene the lights belongs to
         */
        function SpotLight(name, position, direction, angle, exponent, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._innerAngle = 0;
            _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
            _this._projectionTextureLightNear = 1e-6;
            _this._projectionTextureLightFar = 1000.0;
            _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
            _this._projectionTextureViewLightDirty = true;
            _this._projectionTextureProjectionLightDirty = true;
            _this._projectionTextureDirty = true;
            _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
            _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
            _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
            _this._projectionTextureScalingMatrix = BABYLON.Matrix.FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
            _this.position = position;
            _this.direction = direction;
            _this.angle = angle;
            _this.exponent = exponent;
            return _this;
        }
        Object.defineProperty(SpotLight.prototype, "angle", {
            /**
             * Gets the cone angle of the spot light in Radians.
             */
            get: function () {
                return this._angle;
            },
            /**
             * Sets the cone angle of the spot light in Radians.
             */
            set: function (value) {
                this._angle = value;
                this._cosHalfAngle = Math.cos(value * 0.5);
                this._projectionTextureProjectionLightDirty = true;
                this.forceProjectionMatrixCompute();
                this._computeAngleValues();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "innerAngle", {
            /**
             * Only used in gltf falloff mode, this defines the angle where
             * the directional falloff will start before cutting at angle which could be seen
             * as outer angle.
             */
            get: function () {
                return this._innerAngle;
            },
            /**
             * Only used in gltf falloff mode, this defines the angle where
             * the directional falloff will start before cutting at angle which could be seen
             * as outer angle.
             */
            set: function (value) {
                this._innerAngle = value;
                this._computeAngleValues();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
            /**
             * Allows scaling the angle of the light for shadow generation only.
             */
            get: function () {
                return this._shadowAngleScale;
            },
            /**
             * Allows scaling the angle of the light for shadow generation only.
             */
            set: function (value) {
                this._shadowAngleScale = value;
                this.forceProjectionMatrixCompute();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
            /**
            * Allows reading the projecton texture
            */
            get: function () {
                return this._projectionTextureMatrix;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
            /**
             * Gets the near clip of the Spotlight for texture projection.
             */
            get: function () {
                return this._projectionTextureLightNear;
            },
            /**
             * Sets the near clip of the Spotlight for texture projection.
             */
            set: function (value) {
                this._projectionTextureLightNear = value;
                this._projectionTextureProjectionLightDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
            /**
             * Gets the far clip of the Spotlight for texture projection.
             */
            get: function () {
                return this._projectionTextureLightFar;
            },
            /**
             * Sets the far clip of the Spotlight for texture projection.
             */
            set: function (value) {
                this._projectionTextureLightFar = value;
                this._projectionTextureProjectionLightDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
            /**
             * Gets the Up vector of the Spotlight for texture projection.
             */
            get: function () {
                return this._projectionTextureUpDirection;
            },
            /**
             * Sets the Up vector of the Spotlight for texture projection.
             */
            set: function (value) {
                this._projectionTextureUpDirection = value;
                this._projectionTextureProjectionLightDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpotLight.prototype, "projectionTexture", {
            /**
             * Gets the projection texture of the light.
            */
            get: function () {
                return this._projectionTexture;
            },
            /**
            * Sets the projection texture of the light.
            */
            set: function (value) {
                this._projectionTexture = value;
                this._projectionTextureDirty = true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "SpotLight".
         * @returns the class name
         */
        SpotLight.prototype.getClassName = function () {
            return "SpotLight";
        };
        /**
         * Returns the integer 2.
         * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
         */
        SpotLight.prototype.getTypeID = function () {
            return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
        };
        /**
         * Overrides the direction setter to recompute the projection texture view light Matrix.
         */
        SpotLight.prototype._setDirection = function (value) {
            _super.prototype._setDirection.call(this, value);
            this._projectionTextureViewLightDirty = true;
        };
        /**
         * Overrides the position setter to recompute the projection texture view light Matrix.
         */
        SpotLight.prototype._setPosition = function (value) {
            _super.prototype._setPosition.call(this, value);
            this._projectionTextureViewLightDirty = true;
        };
        /**
         * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
         * Returns the SpotLight.
         */
        SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
            var activeCamera = this.getScene().activeCamera;
            if (!activeCamera) {
                return;
            }
            this._shadowAngleScale = this._shadowAngleScale || 1;
            var angle = this._shadowAngleScale * this._angle;
            BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
        };
        SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
            this._projectionTextureViewLightDirty = false;
            this._projectionTextureDirty = true;
            this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
            BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
        };
        SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
            this._projectionTextureProjectionLightDirty = false;
            this._projectionTextureDirty = true;
            var light_far = this.projectionTextureLightFar;
            var light_near = this.projectionTextureLightNear;
            var P = light_far / (light_far - light_near);
            var Q = -P * light_near;
            var S = 1.0 / Math.tan(this._angle / 2.0);
            var A = 1.0;
            BABYLON.Matrix.FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
        };
        /**
         * Main function for light texture projection matrix computing.
         */
        SpotLight.prototype._computeProjectionTextureMatrix = function () {
            this._projectionTextureDirty = false;
            this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
            this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
        };
        SpotLight.prototype._buildUniformLayout = function () {
            this._uniformBuffer.addUniform("vLightData", 4);
            this._uniformBuffer.addUniform("vLightDiffuse", 4);
            this._uniformBuffer.addUniform("vLightSpecular", 3);
            this._uniformBuffer.addUniform("vLightDirection", 3);
            this._uniformBuffer.addUniform("vLightFalloff", 4);
            this._uniformBuffer.addUniform("shadowsInfo", 3);
            this._uniformBuffer.addUniform("depthValues", 2);
            this._uniformBuffer.create();
        };
        SpotLight.prototype._computeAngleValues = function () {
            this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
            this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
        };
        /**
         * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
         * @param effect The effect to update
         * @param lightIndex The index of the light in the effect to update
         * @returns The spot light
         */
        SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
            var normalizeDirection;
            if (this.computeTransformedInformation()) {
                this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
                normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
            }
            else {
                this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
                normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
            }
            this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
            this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
            if (this.projectionTexture && this.projectionTexture.isReady()) {
                if (this._projectionTextureViewLightDirty) {
                    this._computeProjectionTextureViewLightMatrix();
                }
                if (this._projectionTextureProjectionLightDirty) {
                    this._computeProjectionTextureProjectionLightMatrix();
                }
                if (this._projectionTextureDirty) {
                    this._computeProjectionTextureMatrix();
                }
                effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
                effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
            }
            return this;
        };
        /**
         * Disposes the light and the associated resources.
         */
        SpotLight.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            if (this._projectionTexture) {
                this._projectionTexture.dispose();
            }
        };
        /**
         * Prepares the list of defines specific to the light type.
         * @param defines the list of defines
         * @param lightIndex defines the index of the light for the effect
         */
        SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
            defines["SPOTLIGHT" + lightIndex] = true;
            defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
        };
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "angle", null);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "innerAngle", null);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "shadowAngleScale", null);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "exponent", void 0);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "projectionTextureLightNear", null);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "projectionTextureLightFar", null);
        __decorate([
            BABYLON.serialize()
        ], SpotLight.prototype, "projectionTextureUpDirection", null);
        __decorate([
            BABYLON.serializeAsTexture("projectedLightTexture")
        ], SpotLight.prototype, "_projectionTexture", void 0);
        return SpotLight;
    }(BABYLON.ShadowLight));
    BABYLON.SpotLight = SpotLight;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.spotLight.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to override all child animations of a given target
     */
    var AnimationPropertiesOverride = /** @class */ (function () {
        function AnimationPropertiesOverride() {
            /**
             * Gets or sets a value indicating if animation blending must be used
             */
            this.enableBlending = false;
            /**
             * Gets or sets the blending speed to use when enableBlending is true
             */
            this.blendingSpeed = 0.01;
            /**
             * Gets or sets the default loop mode to use
             */
            this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
        }
        return AnimationPropertiesOverride;
    }());
    BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.animationPropertiesOverride.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Represents the range of an animation
     */
    var AnimationRange = /** @class */ (function () {
        /**
         * Initializes the range of an animation
         * @param name The name of the animation range
         * @param from The starting frame of the animation
         * @param to The ending frame of the animation
         */
        function AnimationRange(
        /**The name of the animation range**/
        name, 
        /**The starting frame of the animation */
        from, 
        /**The ending frame of the animation*/
        to) {
            this.name = name;
            this.from = from;
            this.to = to;
        }
        /**
         * Makes a copy of the animation range
         * @returns A copy of the animation range
         */
        AnimationRange.prototype.clone = function () {
            return new AnimationRange(this.name, this.from, this.to);
        };
        return AnimationRange;
    }());
    BABYLON.AnimationRange = AnimationRange;
    /**
     * Composed of a frame, and an action function
     */
    var AnimationEvent = /** @class */ (function () {
        /**
         * Initializes the animation event
         * @param frame The frame for which the event is triggered
         * @param action The event to perform when triggered
         * @param onlyOnce Specifies if the event should be triggered only once
         */
        function AnimationEvent(
        /** The frame for which the event is triggered **/
        frame, 
        /** The event to perform when triggered **/
        action, 
        /** Specifies if the event should be triggered only once**/
        onlyOnce) {
            this.frame = frame;
            this.action = action;
            this.onlyOnce = onlyOnce;
            /**
             * Specifies if the animation event is done
             */
            this.isDone = false;
        }
        /** @hidden */
        AnimationEvent.prototype._clone = function () {
            return new AnimationEvent(this.frame, this.action, this.onlyOnce);
        };
        return AnimationEvent;
    }());
    BABYLON.AnimationEvent = AnimationEvent;
    /**
     * A cursor which tracks a point on a path
     */
    var PathCursor = /** @class */ (function () {
        /**
         * Initializes the path cursor
         * @param path The path to track
         */
        function PathCursor(path) {
            this.path = path;
            /**
             * Stores path cursor callbacks for when an onchange event is triggered
             */
            this._onchange = new Array();
            /**
             * The value of the path cursor
             */
            this.value = 0;
            /**
             * The animation array of the path cursor
             */
            this.animations = new Array();
        }
        /**
         * Gets the cursor point on the path
         * @returns A point on the path cursor at the cursor location
         */
        PathCursor.prototype.getPoint = function () {
            var point = this.path.getPointAtLengthPosition(this.value);
            return new BABYLON.Vector3(point.x, 0, point.y);
        };
        /**
         * Moves the cursor ahead by the step amount
         * @param step The amount to move the cursor forward
         * @returns This path cursor
         */
        PathCursor.prototype.moveAhead = function (step) {
            if (step === void 0) { step = 0.002; }
            this.move(step);
            return this;
        };
        /**
         * Moves the cursor behind by the step amount
         * @param step The amount to move the cursor back
         * @returns This path cursor
         */
        PathCursor.prototype.moveBack = function (step) {
            if (step === void 0) { step = 0.002; }
            this.move(-step);
            return this;
        };
        /**
         * Moves the cursor by the step amount
         * If the step amount is greater than one, an exception is thrown
         * @param step The amount to move the cursor
         * @returns This path cursor
         */
        PathCursor.prototype.move = function (step) {
            if (Math.abs(step) > 1) {
                throw "step size should be less than 1.";
            }
            this.value += step;
            this.ensureLimits();
            this.raiseOnChange();
            return this;
        };
        /**
         * Ensures that the value is limited between zero and one
         * @returns This path cursor
         */
        PathCursor.prototype.ensureLimits = function () {
            while (this.value > 1) {
                this.value -= 1;
            }
            while (this.value < 0) {
                this.value += 1;
            }
            return this;
        };
        /**
         * Runs onchange callbacks on change (used by the animation engine)
         * @returns This path cursor
         */
        PathCursor.prototype.raiseOnChange = function () {
            var _this = this;
            this._onchange.forEach(function (f) { return f(_this); });
            return this;
        };
        /**
         * Executes a function on change
         * @param f A path cursor onchange callback
         * @returns This path cursor
         */
        PathCursor.prototype.onchange = function (f) {
            this._onchange.push(f);
            return this;
        };
        return PathCursor;
    }());
    BABYLON.PathCursor = PathCursor;
    /**
     * Enum for the animation key frame interpolation type
     */
    var AnimationKeyInterpolation;
    (function (AnimationKeyInterpolation) {
        /**
         * Do not interpolate between keys and use the start key value only. Tangents are ignored
         */
        AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
    })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
    /**
     * Class used to store any kind of animation
     */
    var Animation = /** @class */ (function () {
        /**
         * Initializes the animation
         * @param name Name of the animation
         * @param targetProperty Property to animate
         * @param framePerSecond The frames per second of the animation
         * @param dataType The data type of the animation
         * @param loopMode The loop mode of the animation
         * @param enableBlendings Specifies if blending should be enabled
         */
        function Animation(
        /**Name of the animation */
        name, 
        /**Property to animate */
        targetProperty, 
        /**The frames per second of the animation */
        framePerSecond, 
        /**The data type of the animation */
        dataType, 
        /**The loop mode of the animation */
        loopMode, 
        /**Specifies if blending should be enabled */
        enableBlending) {
            this.name = name;
            this.targetProperty = targetProperty;
            this.framePerSecond = framePerSecond;
            this.dataType = dataType;
            this.loopMode = loopMode;
            this.enableBlending = enableBlending;
            /**
             * @hidden Internal use only
             */
            this._runtimeAnimations = new Array();
            /**
             * The set of event that will be linked to this animation
             */
            this._events = new Array();
            /**
             * Stores the blending speed of the animation
             */
            this.blendingSpeed = 0.01;
            /**
             * Stores the animation ranges for the animation
             */
            this._ranges = {};
            this.targetPropertyPath = targetProperty.split(".");
            this.dataType = dataType;
            this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
        }
        /**
         * @hidden Internal use
         */
        Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
            var dataType = undefined;
            if (!isNaN(parseFloat(from)) && isFinite(from)) {
                dataType = Animation.ANIMATIONTYPE_FLOAT;
            }
            else if (from instanceof BABYLON.Quaternion) {
                dataType = Animation.ANIMATIONTYPE_QUATERNION;
            }
            else if (from instanceof BABYLON.Vector3) {
                dataType = Animation.ANIMATIONTYPE_VECTOR3;
            }
            else if (from instanceof BABYLON.Vector2) {
                dataType = Animation.ANIMATIONTYPE_VECTOR2;
            }
            else if (from instanceof BABYLON.Color3) {
                dataType = Animation.ANIMATIONTYPE_COLOR3;
            }
            else if (from instanceof BABYLON.Size) {
                dataType = Animation.ANIMATIONTYPE_SIZE;
            }
            if (dataType == undefined) {
                return null;
            }
            var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
            var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
            animation.setKeys(keys);
            if (easingFunction !== undefined) {
                animation.setEasingFunction(easingFunction);
            }
            return animation;
        };
        /**
         * Sets up an animation
         * @param property The property to animate
         * @param animationType The animation type to apply
         * @param framePerSecond The frames per second of the animation
         * @param easingFunction The easing function used in the animation
         * @returns The created animation
         */
        Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
            var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
            animation.setEasingFunction(easingFunction);
            return animation;
        };
        /**
         * Create and start an animation on a node
         * @param name defines the name of the global animation that will be run on all nodes
         * @param node defines the root node where the animation will take place
         * @param targetProperty defines property to animate
         * @param framePerSecond defines the number of frame per second yo use
         * @param totalFrame defines the number of frames in total
         * @param from defines the initial value
         * @param to defines the final value
         * @param loopMode defines which loop mode you want to use (off by default)
         * @param easingFunction defines the easing function to use (linear by default)
         * @param onAnimationEnd defines the callback to call when animation end
         * @returns the animatable created for this animation
         */
        Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
            var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
            if (!animation) {
                return null;
            }
            return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
        };
        /**
         * Create and start an animation on a node and its descendants
         * @param name defines the name of the global animation that will be run on all nodes
         * @param node defines the root node where the animation will take place
         * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used
         * @param targetProperty defines property to animate
         * @param framePerSecond defines the number of frame per second to use
         * @param totalFrame defines the number of frames in total
         * @param from defines the initial value
         * @param to defines the final value
         * @param loopMode defines which loop mode you want to use (off by default)
         * @param easingFunction defines the easing function to use (linear by default)
         * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
         * @returns the list of animatables created for all nodes
         * @example https://www.babylonjs-playground.com/#MH0VLI
         */
        Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
            var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
            if (!animation) {
                return null;
            }
            var scene = node.getScene();
            return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
        };
        /**
         * Creates a new animation, merges it with the existing animations and starts it
         * @param name Name of the animation
         * @param node Node which contains the scene that begins the animations
         * @param targetProperty Specifies which property to animate
         * @param framePerSecond The frames per second of the animation
         * @param totalFrame The total number of frames
         * @param from The frame at the beginning of the animation
         * @param to The frame at the end of the animation
         * @param loopMode Specifies the loop mode of the animation
         * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
         * @param onAnimationEnd Callback to run once the animation is complete
         * @returns Nullable animation
         */
        Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
            var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
            if (!animation) {
                return null;
            }
            node.animations.push(animation);
            return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
        };
        /**
         * Transition property of an host to the target Value
         * @param property The property to transition
         * @param targetValue The target Value of the property
         * @param host The object where the property to animate belongs
         * @param scene Scene used to run the animation
         * @param frameRate Framerate (in frame/s) to use
         * @param transition The transition type we want to use
         * @param duration The duration of the animation, in milliseconds
         * @param onAnimationEnd Callback trigger at the end of the animation
         * @returns Nullable animation
         */
        Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
            if (onAnimationEnd === void 0) { onAnimationEnd = null; }
            if (duration <= 0) {
                host[property] = targetValue;
                if (onAnimationEnd) {
                    onAnimationEnd();
                }
                return null;
            }
            var endFrame = frameRate * (duration / 1000);
            transition.setKeys([{
                    frame: 0,
                    value: host[property].clone ? host[property].clone() : host[property]
                },
                {
                    frame: endFrame,
                    value: targetValue
                }]);
            if (!host.animations) {
                host.animations = [];
            }
            host.animations.push(transition);
            var animation = scene.beginAnimation(host, 0, endFrame, false);
            animation.onAnimationEnd = onAnimationEnd;
            return animation;
        };
        Object.defineProperty(Animation.prototype, "runtimeAnimations", {
            /**
             * Return the array of runtime animations currently using this animation
             */
            get: function () {
                return this._runtimeAnimations;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
            /**
             * Specifies if any of the runtime animations are currently running
             */
            get: function () {
                for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
                    var runtimeAnimation = _a[_i];
                    if (!runtimeAnimation.isStopped) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * Converts the animation to a string
         * @param fullDetails support for multiple levels of logging within scene loading
         * @returns String form of the animation
         */
        Animation.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name + ", property: " + this.targetProperty;
            ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
            ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
            ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
            if (fullDetails) {
                ret += ", Ranges: {";
                var first = true;
                for (var name in this._ranges) {
                    if (first) {
                        ret += ", ";
                        first = false;
                    }
                    ret += name;
                }
                ret += "}";
            }
            return ret;
        };
        /**
         * Add an event to this animation
         * @param event Event to add
         */
        Animation.prototype.addEvent = function (event) {
            this._events.push(event);
        };
        /**
         * Remove all events found at the given frame
         * @param frame The frame to remove events from
         */
        Animation.prototype.removeEvents = function (frame) {
            for (var index = 0; index < this._events.length; index++) {
                if (this._events[index].frame === frame) {
                    this._events.splice(index, 1);
                    index--;
                }
            }
        };
        /**
         * Retrieves all the events from the animation
         * @returns Events from the animation
         */
        Animation.prototype.getEvents = function () {
            return this._events;
        };
        /**
         * Creates an animation range
         * @param name Name of the animation range
         * @param from Starting frame of the animation range
         * @param to Ending frame of the animation
         */
        Animation.prototype.createRange = function (name, from, to) {
            // check name not already in use; could happen for bones after serialized
            if (!this._ranges[name]) {
                this._ranges[name] = new AnimationRange(name, from, to);
            }
        };
        /**
         * Deletes an animation range by name
         * @param name Name of the animation range to delete
         * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
         */
        Animation.prototype.deleteRange = function (name, deleteFrames) {
            if (deleteFrames === void 0) { deleteFrames = true; }
            var range = this._ranges[name];
            if (!range) {
                return;
            }
            if (deleteFrames) {
                var from = range.from;
                var to = range.to;
                // this loop MUST go high to low for multiple splices to work
                for (var key = this._keys.length - 1; key >= 0; key--) {
                    if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
                        this._keys.splice(key, 1);
                    }
                }
            }
            this._ranges[name] = null; // said much faster than 'delete this._range[name]'
        };
        /**
         * Gets the animation range by name, or null if not defined
         * @param name Name of the animation range
         * @returns Nullable animation range
         */
        Animation.prototype.getRange = function (name) {
            return this._ranges[name];
        };
        /**
         * Gets the key frames from the animation
         * @returns The key frames of the animation
         */
        Animation.prototype.getKeys = function () {
            return this._keys;
        };
        /**
         * Gets the highest frame rate of the animation
         * @returns Highest frame rate of the animation
         */
        Animation.prototype.getHighestFrame = function () {
            var ret = 0;
            for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
                if (ret < this._keys[key].frame) {
                    ret = this._keys[key].frame;
                }
            }
            return ret;
        };
        /**
         * Gets the easing function of the animation
         * @returns Easing function of the animation
         */
        Animation.prototype.getEasingFunction = function () {
            return this._easingFunction;
        };
        /**
         * Sets the easing function of the animation
         * @param easingFunction A custom mathematical formula for animation
         */
        Animation.prototype.setEasingFunction = function (easingFunction) {
            this._easingFunction = easingFunction;
        };
        /**
         * Interpolates a scalar linearly
         * @param startValue Start value of the animation curve
         * @param endValue End value of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated scalar value
         */
        Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
        };
        /**
         * Interpolates a scalar cubically
         * @param startValue Start value of the animation curve
         * @param outTangent End tangent of the animation
         * @param endValue End value of the animation curve
         * @param inTangent Start tangent of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated scalar value
         */
        Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
            return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
        };
        /**
         * Interpolates a quaternion using a spherical linear interpolation
         * @param startValue Start value of the animation curve
         * @param endValue End value of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated quaternion value
         */
        Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
        };
        /**
         * Interpolates a quaternion cubically
         * @param startValue Start value of the animation curve
         * @param outTangent End tangent of the animation curve
         * @param endValue End value of the animation curve
         * @param inTangent Start tangent of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated quaternion value
         */
        Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
            return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
        };
        /**
         * Interpolates a Vector3 linearl
         * @param startValue Start value of the animation curve
         * @param endValue End value of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated scalar value
         */
        Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
        };
        /**
         * Interpolates a Vector3 cubically
         * @param startValue Start value of the animation curve
         * @param outTangent End tangent of the animation
         * @param endValue End value of the animation curve
         * @param inTangent Start tangent of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns InterpolatedVector3 value
         */
        Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
            return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
        };
        /**
         * Interpolates a Vector2 linearly
         * @param startValue Start value of the animation curve
         * @param endValue End value of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated Vector2 value
         */
        Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
        };
        /**
         * Interpolates a Vector2 cubically
         * @param startValue Start value of the animation curve
         * @param outTangent End tangent of the animation
         * @param endValue End value of the animation curve
         * @param inTangent Start tangent of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated Vector2 value
         */
        Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
            return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
        };
        /**
         * Interpolates a size linearly
         * @param startValue Start value of the animation curve
         * @param endValue End value of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated Size value
         */
        Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Size.Lerp(startValue, endValue, gradient);
        };
        /**
         * Interpolates a Color3 linearly
         * @param startValue Start value of the animation curve
         * @param endValue End value of the animation curve
         * @param gradient Scalar amount to interpolate
         * @returns Interpolated Color3 value
         */
        Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
            return BABYLON.Color3.Lerp(startValue, endValue, gradient);
        };
        /**
         * @hidden Internal use only
         */
        Animation.prototype._getKeyValue = function (value) {
            if (typeof value === "function") {
                return value();
            }
            return value;
        };
        /**
         * @hidden Internal use only
         */
        Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
            if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
                return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
            }
            var keys = this.getKeys();
            // Try to get a hash to find the right key
            var startKeyIndex = Math.max(0, Math.min(keys.length - 1, Math.floor(keys.length * (currentFrame - keys[0].frame) / (keys[keys.length - 1].frame - keys[0].frame)) - 1));
            if (keys[startKeyIndex].frame >= currentFrame) {
                while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
                    startKeyIndex--;
                }
            }
            for (var key = startKeyIndex; key < keys.length; key++) {
                var endKey = keys[key + 1];
                if (endKey.frame >= currentFrame) {
                    var startKey = keys[key];
                    var startValue = this._getKeyValue(startKey.value);
                    if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
                        return startValue;
                    }
                    var endValue = this._getKeyValue(endKey.value);
                    var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
                    var frameDelta = endKey.frame - startKey.frame;
                    // gradient : percent of currentFrame between the frame inf and the frame sup
                    var gradient = (currentFrame - startKey.frame) / frameDelta;
                    // check for easingFunction and correction of gradient
                    var easingFunction = this.getEasingFunction();
                    if (easingFunction != null) {
                        gradient = easingFunction.ease(gradient);
                    }
                    switch (this.dataType) {
                        // Float
                        case Animation.ANIMATIONTYPE_FLOAT:
                            var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return floatValue;
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return offsetValue * repeatCount + floatValue;
                            }
                            break;
                        // Quaternion
                        case Animation.ANIMATIONTYPE_QUATERNION:
                            var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return quatValue;
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return quatValue.addInPlace(offsetValue.scale(repeatCount));
                            }
                            return quatValue;
                        // Vector3
                        case Animation.ANIMATIONTYPE_VECTOR3:
                            var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return vec3Value;
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return vec3Value.add(offsetValue.scale(repeatCount));
                            }
                        // Vector2
                        case Animation.ANIMATIONTYPE_VECTOR2:
                            var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return vec2Value;
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return vec2Value.add(offsetValue.scale(repeatCount));
                            }
                        // Size
                        case Animation.ANIMATIONTYPE_SIZE:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.sizeInterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                            }
                        // Color3
                        case Animation.ANIMATIONTYPE_COLOR3:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    return this.color3InterpolateFunction(startValue, endValue, gradient);
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
                            }
                        // Matrix
                        case Animation.ANIMATIONTYPE_MATRIX:
                            switch (loopMode) {
                                case Animation.ANIMATIONLOOPMODE_CYCLE:
                                case Animation.ANIMATIONLOOPMODE_CONSTANT:
                                    if (Animation.AllowMatricesInterpolation) {
                                        return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
                                    }
                                case Animation.ANIMATIONLOOPMODE_RELATIVE:
                                    return startValue;
                            }
                        default:
                            break;
                    }
                    break;
                }
            }
            return this._getKeyValue(keys[keys.length - 1].value);
        };
        /**
         * Defines the function to use to interpolate matrices
         * @param startValue defines the start matrix
         * @param endValue defines the end matrix
         * @param gradient defines the gradient between both matrices
         * @param result defines an optional target matrix where to store the interpolation
         * @returns the interpolated matrix
         */
        Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
            if (Animation.AllowMatrixDecomposeForInterpolation) {
                if (result) {
                    BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
                    return result;
                }
                return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
            }
            if (result) {
                BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
                return result;
            }
            return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
        };
        /**
         * Makes a copy of the animation
         * @returns Cloned animation
         */
        Animation.prototype.clone = function () {
            var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
            clone.enableBlending = this.enableBlending;
            clone.blendingSpeed = this.blendingSpeed;
            if (this._keys) {
                clone.setKeys(this._keys);
            }
            if (this._ranges) {
                clone._ranges = {};
                for (var name in this._ranges) {
                    var range = this._ranges[name];
                    if (!range) {
                        continue;
                    }
                    clone._ranges[name] = range.clone();
                }
            }
            return clone;
        };
        /**
         * Sets the key frames of the animation
         * @param values The animation key frames to set
         */
        Animation.prototype.setKeys = function (values) {
            this._keys = values.slice(0);
        };
        /**
         * Serializes the animation to an object
         * @returns Serialized object
         */
        Animation.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.property = this.targetProperty;
            serializationObject.framePerSecond = this.framePerSecond;
            serializationObject.dataType = this.dataType;
            serializationObject.loopBehavior = this.loopMode;
            serializationObject.enableBlending = this.enableBlending;
            serializationObject.blendingSpeed = this.blendingSpeed;
            var dataType = this.dataType;
            serializationObject.keys = [];
            var keys = this.getKeys();
            for (var index = 0; index < keys.length; index++) {
                var animationKey = keys[index];
                var key = {};
                key.frame = animationKey.frame;
                switch (dataType) {
                    case Animation.ANIMATIONTYPE_FLOAT:
                        key.values = [animationKey.value];
                        break;
                    case Animation.ANIMATIONTYPE_QUATERNION:
                    case Animation.ANIMATIONTYPE_MATRIX:
                    case Animation.ANIMATIONTYPE_VECTOR3:
                    case Animation.ANIMATIONTYPE_COLOR3:
                        key.values = animationKey.value.asArray();
                        break;
                }
                serializationObject.keys.push(key);
            }
            serializationObject.ranges = [];
            for (var name in this._ranges) {
                var source = this._ranges[name];
                if (!source) {
                    continue;
                }
                var range = {};
                range.name = name;
                range.from = source.from;
                range.to = source.to;
                serializationObject.ranges.push(range);
            }
            return serializationObject;
        };
        Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
            /**
             * Get the float animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_FLOAT;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
            /**
             * Get the Vector3 animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_VECTOR3;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
            /**
             * Get the Vector2 animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_VECTOR2;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
            /**
             * Get the Size animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_SIZE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
            /**
             * Get the Quaternion animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_QUATERNION;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
            /**
             * Get the Matrix animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_MATRIX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
            /**
             * Get the Color3 animation type
             */
            get: function () {
                return Animation._ANIMATIONTYPE_COLOR3;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
            /**
             * Get the Relative Loop Mode
             */
            get: function () {
                return Animation._ANIMATIONLOOPMODE_RELATIVE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
            /**
             * Get the Cycle Loop Mode
             */
            get: function () {
                return Animation._ANIMATIONLOOPMODE_CYCLE;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
            /**
             * Get the Constant Loop Mode
             */
            get: function () {
                return Animation._ANIMATIONLOOPMODE_CONSTANT;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        Animation._UniversalLerp = function (left, right, amount) {
            var constructor = left.constructor;
            if (constructor.Lerp) { // Lerp supported
                return constructor.Lerp(left, right, amount);
            }
            else if (constructor.Slerp) { // Slerp supported
                return constructor.Slerp(left, right, amount);
            }
            else if (left.toFixed) { // Number
                return left * (1.0 - amount) + amount * right;
            }
            else { // Blending not supported
                return right;
            }
        };
        /**
         * Parses an animation object and creates an animation
         * @param parsedAnimation Parsed animation object
         * @returns Animation object
         */
        Animation.Parse = function (parsedAnimation) {
            var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
            var dataType = parsedAnimation.dataType;
            var keys = [];
            var data;
            var index;
            if (parsedAnimation.enableBlending) {
                animation.enableBlending = parsedAnimation.enableBlending;
            }
            if (parsedAnimation.blendingSpeed) {
                animation.blendingSpeed = parsedAnimation.blendingSpeed;
            }
            for (index = 0; index < parsedAnimation.keys.length; index++) {
                var key = parsedAnimation.keys[index];
                var inTangent;
                var outTangent;
                switch (dataType) {
                    case Animation.ANIMATIONTYPE_FLOAT:
                        data = key.values[0];
                        if (key.values.length >= 1) {
                            inTangent = key.values[1];
                        }
                        if (key.values.length >= 2) {
                            outTangent = key.values[2];
                        }
                        break;
                    case Animation.ANIMATIONTYPE_QUATERNION:
                        data = BABYLON.Quaternion.FromArray(key.values);
                        if (key.values.length >= 8) {
                            var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
                            if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
                                inTangent = _inTangent;
                            }
                        }
                        if (key.values.length >= 12) {
                            var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
                            if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
                                outTangent = _outTangent;
                            }
                        }
                        break;
                    case Animation.ANIMATIONTYPE_MATRIX:
                        data = BABYLON.Matrix.FromArray(key.values);
                        break;
                    case Animation.ANIMATIONTYPE_COLOR3:
                        data = BABYLON.Color3.FromArray(key.values);
                        break;
                    case Animation.ANIMATIONTYPE_VECTOR3:
                    default:
                        data = BABYLON.Vector3.FromArray(key.values);
                        break;
                }
                var keyData = {};
                keyData.frame = key.frame;
                keyData.value = data;
                if (inTangent != undefined) {
                    keyData.inTangent = inTangent;
                }
                if (outTangent != undefined) {
                    keyData.outTangent = outTangent;
                }
                keys.push(keyData);
            }
            animation.setKeys(keys);
            if (parsedAnimation.ranges) {
                for (index = 0; index < parsedAnimation.ranges.length; index++) {
                    data = parsedAnimation.ranges[index];
                    animation.createRange(data.name, data.from, data.to);
                }
            }
            return animation;
        };
        /**
         * Appends the serialized animations from the source animations
         * @param source Source containing the animations
         * @param destination Target to store the animations
         */
        Animation.AppendSerializedAnimations = function (source, destination) {
            if (source.animations) {
                destination.animations = [];
                for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
                    var animation = source.animations[animationIndex];
                    destination.animations.push(animation.serialize());
                }
            }
        };
        /**
         * Use matrix interpolation instead of using direct key value when animating matrices
         */
        Animation.AllowMatricesInterpolation = false;
        /**
         * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
         */
        Animation.AllowMatrixDecomposeForInterpolation = true;
        // Statics
        /**
         * Float animation type
         */
        Animation._ANIMATIONTYPE_FLOAT = 0;
        /**
         * Vector3 animation type
         */
        Animation._ANIMATIONTYPE_VECTOR3 = 1;
        /**
         * Quaternion animation type
         */
        Animation._ANIMATIONTYPE_QUATERNION = 2;
        /**
         * Matrix animation type
         */
        Animation._ANIMATIONTYPE_MATRIX = 3;
        /**
         * Color3 animation type
         */
        Animation._ANIMATIONTYPE_COLOR3 = 4;
        /**
         * Vector2 animation type
         */
        Animation._ANIMATIONTYPE_VECTOR2 = 5;
        /**
         * Size animation type
         */
        Animation._ANIMATIONTYPE_SIZE = 6;
        /**
         * Relative Loop Mode
         */
        Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
        /**
         * Cycle Loop Mode
         */
        Animation._ANIMATIONLOOPMODE_CYCLE = 1;
        /**
         * Constant Loop Mode
         */
        Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
        return Animation;
    }());
    BABYLON.Animation = Animation;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.animation.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class defines the direct association between an animation and a target
     */
    var TargetedAnimation = /** @class */ (function () {
        function TargetedAnimation() {
        }
        return TargetedAnimation;
    }());
    BABYLON.TargetedAnimation = TargetedAnimation;
    /**
     * Use this class to create coordinated animations on multiple targets
     */
    var AnimationGroup = /** @class */ (function () {
        /**
         * Instantiates a new Animation Group.
         * This helps managing several animations at once.
         * @see http://doc.babylonjs.com/how_to/group
         * @param name Defines the name of the group
         * @param scene Defines the scene the group belongs to
         */
        function AnimationGroup(
        /** The name of the animation group */
        name, scene) {
            if (scene === void 0) { scene = null; }
            this.name = name;
            this._targetedAnimations = new Array();
            this._animatables = new Array();
            this._from = Number.MAX_VALUE;
            this._to = -Number.MAX_VALUE;
            this._speedRatio = 1;
            /**
             * This observable will notify when one animation have ended.
             */
            this.onAnimationEndObservable = new BABYLON.Observable();
            /**
             * This observable will notify when all animations have ended.
             */
            this.onAnimationGroupEndObservable = new BABYLON.Observable();
            /**
             * This observable will notify when all animations have paused.
             */
            this.onAnimationGroupPauseObservable = new BABYLON.Observable();
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            this._scene.animationGroups.push(this);
        }
        Object.defineProperty(AnimationGroup.prototype, "from", {
            /**
             * Gets the first frame
             */
            get: function () {
                return this._from;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AnimationGroup.prototype, "to", {
            /**
             * Gets the last frame
             */
            get: function () {
                return this._to;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AnimationGroup.prototype, "isStarted", {
            /**
             * Define if the animations are started
             */
            get: function () {
                return this._isStarted;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
            /**
             * Gets or sets the speed ratio to use for all animations
             */
            get: function () {
                return this._speedRatio;
            },
            /**
             * Gets or sets the speed ratio to use for all animations
             */
            set: function (value) {
                if (this._speedRatio === value) {
                    return;
                }
                this._speedRatio = value;
                for (var index = 0; index < this._animatables.length; index++) {
                    var animatable = this._animatables[index];
                    animatable.speedRatio = this._speedRatio;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
            /**
             * Gets the targeted animations for this animation group
             */
            get: function () {
                return this._targetedAnimations;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AnimationGroup.prototype, "animatables", {
            /**
             * returning the list of animatables controlled by this animation group.
             */
            get: function () {
                return this._animatables;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Add an animation (with its target) in the group
         * @param animation defines the animation we want to add
         * @param target defines the target of the animation
         * @returns the TargetedAnimation object
         */
        AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
            var targetedAnimation = {
                animation: animation,
                target: target
            };
            var keys = animation.getKeys();
            if (this._from > keys[0].frame) {
                this._from = keys[0].frame;
            }
            if (this._to < keys[keys.length - 1].frame) {
                this._to = keys[keys.length - 1].frame;
            }
            this._targetedAnimations.push(targetedAnimation);
            return targetedAnimation;
        };
        /**
         * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
         * It can add constant keys at begin or end
         * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
         * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
         * @returns the animation group
         */
        AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
            if (beginFrame === void 0) { beginFrame = null; }
            if (endFrame === void 0) { endFrame = null; }
            if (beginFrame == null) {
                beginFrame = this._from;
            }
            if (endFrame == null) {
                endFrame = this._to;
            }
            for (var index = 0; index < this._targetedAnimations.length; index++) {
                var targetedAnimation = this._targetedAnimations[index];
                var keys = targetedAnimation.animation.getKeys();
                var startKey = keys[0];
                var endKey = keys[keys.length - 1];
                if (startKey.frame > beginFrame) {
                    var newKey = {
                        frame: beginFrame,
                        value: startKey.value,
                        inTangent: startKey.inTangent,
                        outTangent: startKey.outTangent,
                        interpolation: startKey.interpolation
                    };
                    keys.splice(0, 0, newKey);
                }
                if (endKey.frame < endFrame) {
                    var newKey = {
                        frame: endFrame,
                        value: endKey.value,
                        inTangent: endKey.outTangent,
                        outTangent: endKey.outTangent,
                        interpolation: endKey.interpolation
                    };
                    keys.push(newKey);
                }
            }
            this._from = beginFrame;
            this._to = endFrame;
            return this;
        };
        /**
         * Start all animations on given targets
         * @param loop defines if animations must loop
         * @param speedRatio defines the ratio to apply to animation speed (1 by default)
         * @param from defines the from key (optional)
         * @param to defines the to key (optional)
         * @returns the current animation group
         */
        AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
            var _this = this;
            if (loop === void 0) { loop = false; }
            if (speedRatio === void 0) { speedRatio = 1; }
            if (this._isStarted || this._targetedAnimations.length === 0) {
                return this;
            }
            var _loop_1 = function (targetedAnimation) {
                var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
                animatable.onAnimationEnd = function () {
                    _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
                    _this._checkAnimationGroupEnded(animatable);
                };
                this_1._animatables.push(animatable);
            };
            var this_1 = this;
            for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
                var targetedAnimation = _a[_i];
                _loop_1(targetedAnimation);
            }
            this._speedRatio = speedRatio;
            this._isStarted = true;
            return this;
        };
        /**
         * Pause all animations
         * @returns the animation group
         */
        AnimationGroup.prototype.pause = function () {
            if (!this._isStarted) {
                return this;
            }
            for (var index = 0; index < this._animatables.length; index++) {
                var animatable = this._animatables[index];
                animatable.pause();
            }
            this.onAnimationGroupPauseObservable.notifyObservers(this);
            return this;
        };
        /**
         * Play all animations to initial state
         * This function will start() the animations if they were not started or will restart() them if they were paused
         * @param loop defines if animations must loop
         * @returns the animation group
         */
        AnimationGroup.prototype.play = function (loop) {
            // only if all animatables are ready and exist
            if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
                if (loop !== undefined) {
                    for (var index = 0; index < this._animatables.length; index++) {
                        var animatable = this._animatables[index];
                        animatable.loopAnimation = loop;
                    }
                }
                this.restart();
            }
            else {
                this.stop();
                this.start(loop, this._speedRatio);
            }
            return this;
        };
        /**
         * Reset all animations to initial state
         * @returns the animation group
         */
        AnimationGroup.prototype.reset = function () {
            if (!this._isStarted) {
                return this;
            }
            for (var index = 0; index < this._animatables.length; index++) {
                var animatable = this._animatables[index];
                animatable.reset();
            }
            return this;
        };
        /**
         * Restart animations from key 0
         * @returns the animation group
         */
        AnimationGroup.prototype.restart = function () {
            if (!this._isStarted) {
                return this;
            }
            for (var index = 0; index < this._animatables.length; index++) {
                var animatable = this._animatables[index];
                animatable.restart();
            }
            return this;
        };
        /**
         * Stop all animations
         * @returns the animation group
         */
        AnimationGroup.prototype.stop = function () {
            if (!this._isStarted) {
                return this;
            }
            var list = this._animatables.slice();
            for (var index = 0; index < list.length; index++) {
                list[index].stop();
            }
            this._isStarted = false;
            return this;
        };
        /**
         * Set animation weight for all animatables
         * @param weight defines the weight to use
         * @return the animationGroup
         * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
         */
        AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
            for (var index = 0; index < this._animatables.length; index++) {
                var animatable = this._animatables[index];
                animatable.weight = weight;
            }
            return this;
        };
        /**
         * Synchronize and normalize all animatables with a source animatable
         * @param root defines the root animatable to synchronize with
         * @return the animationGroup
         * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
         */
        AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
            for (var index = 0; index < this._animatables.length; index++) {
                var animatable = this._animatables[index];
                animatable.syncWith(root);
            }
            return this;
        };
        /**
         * Goes to a specific frame in this animation group
         * @param frame the frame number to go to
         * @return the animationGroup
         */
        AnimationGroup.prototype.goToFrame = function (frame) {
            if (!this._isStarted) {
                return this;
            }
            for (var index = 0; index < this._animatables.length; index++) {
                var animatable = this._animatables[index];
                animatable.goToFrame(frame);
            }
            return this;
        };
        /**
         * Dispose all associated resources
         */
        AnimationGroup.prototype.dispose = function () {
            this._targetedAnimations = [];
            this._animatables = [];
            var index = this._scene.animationGroups.indexOf(this);
            if (index > -1) {
                this._scene.animationGroups.splice(index, 1);
            }
        };
        AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
            // animatable should be taken out of the array
            var idx = this._animatables.indexOf(animatable);
            if (idx > -1) {
                this._animatables.splice(idx, 1);
            }
            // all animatables were removed? animation group ended!
            if (this._animatables.length === 0) {
                this._isStarted = false;
                this.onAnimationGroupEndObservable.notifyObservers(this);
            }
        };
        // Statics
        /**
         * Returns a new AnimationGroup object parsed from the source provided.
         * @param parsedAnimationGroup defines the source
         * @param scene defines the scene that will receive the animationGroup
         * @returns a new AnimationGroup
         */
        AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
            var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
            for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
                var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
                var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
                var id = targetedAnimation.targetId;
                var targetNode = scene.getNodeByID(id);
                if (targetNode != null) {
                    animationGroup.addTargetedAnimation(animation, targetNode);
                }
            }
            if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null) {
                animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
            }
            return animationGroup;
        };
        /**
         * Returns the string "AnimationGroup"
         * @returns "AnimationGroup"
         */
        AnimationGroup.prototype.getClassName = function () {
            return "AnimationGroup";
        };
        /**
         * Creates a detailled string about the object
         * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
         * @returns a string representing the object
         */
        AnimationGroup.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name;
            ret += ", type: " + this.getClassName();
            if (fullDetails) {
                ret += ", from: " + this._from;
                ret += ", to: " + this._to;
                ret += ", isStarted: " + this._isStarted;
                ret += ", speedRatio: " + this._speedRatio;
                ret += ", targetedAnimations length: " + this._targetedAnimations.length;
                ret += ", animatables length: " + this._animatables;
            }
            return ret;
        };
        return AnimationGroup;
    }());
    BABYLON.AnimationGroup = AnimationGroup;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.animationGroup.js.map

var BABYLON;
(function (BABYLON) {
    // Static values to help the garbage collector
    // Quaternion
    var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
    // Vector3
    var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
    // Vector2
    var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
    // Size
    var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
    // Color3
    var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
    /**
     * Defines a runtime animation
     */
    var RuntimeAnimation = /** @class */ (function () {
        /**
         * Create a new RuntimeAnimation object
         * @param target defines the target of the animation
         * @param animation defines the source animation object
         * @param scene defines the hosting scene
         * @param host defines the initiating Animatable
         */
        function RuntimeAnimation(target, animation, scene, host) {
            var _this = this;
            this._events = new Array();
            /**
             * The current frame of the runtime animation
             */
            this._currentFrame = 0;
            /**
             * The original value of the runtime animation
             */
            this._originalValue = new Array();
            /**
             * The offsets cache of the runtime animation
             */
            this._offsetsCache = {};
            /**
             * The high limits cache of the runtime animation
             */
            this._highLimitsCache = {};
            /**
             * Specifies if the runtime animation has been stopped
             */
            this._stopped = false;
            /**
             * The blending factor of the runtime animation
             */
            this._blendingFactor = 0;
            /**
             * The target path of the runtime animation
             */
            this._targetPath = "";
            /**
             * The weight of the runtime animation
             */
            this._weight = 1.0;
            /**
             * The ratio offset of the runtime animation
             */
            this._ratioOffset = 0;
            /**
             * The previous delay of the runtime animation
             */
            this._previousDelay = 0;
            /**
             * The previous ratio of the runtime animation
             */
            this._previousRatio = 0;
            this._animation = animation;
            this._target = target;
            this._scene = scene;
            this._host = host;
            animation._runtimeAnimations.push(this);
            // Cloning events locally
            var events = animation.getEvents();
            if (events && events.length > 0) {
                events.forEach(function (e) {
                    _this._events.push(e._clone());
                });
            }
        }
        Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
            /**
             * Gets the current frame of the runtime animation
             */
            get: function () {
                return this._currentFrame;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RuntimeAnimation.prototype, "weight", {
            /**
             * Gets the weight of the runtime animation
             */
            get: function () {
                return this._weight;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
            /**
             * Gets the current value of the runtime animation
             */
            get: function () {
                return this._currentValue;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
            /**
             * Gets the target path of the runtime animation
             */
            get: function () {
                return this._targetPath;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RuntimeAnimation.prototype, "target", {
            /**
             * Gets the actual target of the runtime animation
             */
            get: function () {
                return this._activeTarget;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RuntimeAnimation.prototype, "animation", {
            /**
             * Gets the animation from the runtime animation
             */
            get: function () {
                return this._animation;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Resets the runtime animation to the beginning
         * @param restoreOriginal defines whether to restore the target property to the original value
         */
        RuntimeAnimation.prototype.reset = function (restoreOriginal) {
            if (restoreOriginal === void 0) { restoreOriginal = false; }
            if (restoreOriginal) {
                if (this._target instanceof Array) {
                    var index = 0;
                    for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
                        var target = _a[_i];
                        if (this._originalValue[index] !== undefined) {
                            this._setValue(target, this._originalValue[index], -1);
                        }
                        index++;
                    }
                }
                else {
                    if (this._originalValue[0] !== undefined) {
                        this._setValue(this._target, this._originalValue[0], -1);
                    }
                }
            }
            this._offsetsCache = {};
            this._highLimitsCache = {};
            this._currentFrame = 0;
            this._blendingFactor = 0;
            this._originalValue = new Array();
            // Events
            for (var index = 0; index < this._events.length; index++) {
                this._events[index].isDone = false;
            }
        };
        /**
         * Specifies if the runtime animation is stopped
         * @returns Boolean specifying if the runtime animation is stopped
         */
        RuntimeAnimation.prototype.isStopped = function () {
            return this._stopped;
        };
        /**
         * Disposes of the runtime animation
         */
        RuntimeAnimation.prototype.dispose = function () {
            var index = this._animation.runtimeAnimations.indexOf(this);
            if (index > -1) {
                this._animation.runtimeAnimations.splice(index, 1);
            }
        };
        /**
         * Interpolates the animation from the current frame
         * @param currentFrame The frame to interpolate the animation to
         * @param repeatCount The number of times that the animation should loop
         * @param loopMode The type of looping mode to use
         * @param offsetValue Animation offset value
         * @param highLimitValue The high limit value
         * @returns The interpolated value
         */
        RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
            this._currentFrame = currentFrame;
            if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
                this._workValue = BABYLON.Matrix.Zero();
            }
            return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
        };
        /**
         * Apply the interpolated value to the target
         * @param currentValue defines the value computed by the animation
         * @param weight defines the weight to apply to this value (Defaults to 1.0)
         */
        RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
            if (weight === void 0) { weight = 1.0; }
            if (this._target instanceof Array) {
                var index = 0;
                for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
                    var target = _a[_i];
                    this._setValue(target, currentValue, weight, index);
                    index++;
                }
            }
            else {
                this._setValue(this._target, currentValue, weight);
            }
        };
        RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
            if (targetIndex === void 0) { targetIndex = 0; }
            // Set value
            var path;
            var destination;
            var targetPropertyPath = this._animation.targetPropertyPath;
            if (targetPropertyPath.length > 1) {
                var property = target[targetPropertyPath[0]];
                for (var index = 1; index < targetPropertyPath.length - 1; index++) {
                    property = property[targetPropertyPath[index]];
                }
                path = targetPropertyPath[targetPropertyPath.length - 1];
                destination = property;
            }
            else {
                path = targetPropertyPath[0];
                destination = target;
            }
            this._targetPath = path;
            this._activeTarget = destination;
            this._weight = weight;
            if (this._originalValue[targetIndex] === undefined) {
                var originalValue = void 0;
                if (destination.getRestPose && path === "_matrix") { // For bones
                    originalValue = destination.getRestPose();
                }
                else {
                    originalValue = destination[path];
                }
                if (originalValue && originalValue.clone) {
                    this._originalValue[targetIndex] = originalValue.clone();
                }
                else {
                    this._originalValue[targetIndex] = originalValue;
                }
            }
            // Blending
            var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
            if (enableBlending && this._blendingFactor <= 1.0) {
                if (!this._originalBlendValue) {
                    var originalValue = destination[path];
                    if (originalValue.clone) {
                        this._originalBlendValue = originalValue.clone();
                    }
                    else {
                        this._originalBlendValue = originalValue;
                    }
                }
                if (this._originalBlendValue.m) { // Matrix
                    if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
                        if (this._currentValue) {
                            BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
                        }
                        else {
                            this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
                        }
                    }
                    else {
                        if (this._currentValue) {
                            BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
                        }
                        else {
                            this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
                        }
                    }
                }
                else {
                    this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
                }
                var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
                this._blendingFactor += blendingSpeed;
            }
            else {
                this._currentValue = currentValue;
            }
            if (weight !== -1.0) {
                this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
            }
            else {
                destination[path] = this._currentValue;
            }
            if (target.markAsDirty) {
                target.markAsDirty(this._animation.targetProperty);
            }
        };
        /**
         * Gets the loop pmode of the runtime animation
         * @returns Loop Mode
         */
        RuntimeAnimation.prototype._getCorrectLoopMode = function () {
            if (this._target && this._target.animationPropertiesOverride) {
                return this._target.animationPropertiesOverride.loopMode;
            }
            return this._animation.loopMode;
        };
        /**
         * Move the current animation to a given frame
         * @param frame defines the frame to move to
         */
        RuntimeAnimation.prototype.goToFrame = function (frame) {
            var keys = this._animation.getKeys();
            if (frame < keys[0].frame) {
                frame = keys[0].frame;
            }
            else if (frame > keys[keys.length - 1].frame) {
                frame = keys[keys.length - 1].frame;
            }
            var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
            this.setValue(currentValue, -1);
        };
        /**
         * @hidden Internal use only
         */
        RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
            var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
            this._ratioOffset = this._previousRatio - newRatio;
        };
        /**
         * Execute the current animation
         * @param delay defines the delay to add to the current frame
         * @param from defines the lower bound of the animation range
         * @param to defines the upper bound of the animation range
         * @param loop defines if the current animation must loop
         * @param speedRatio defines the current speed ratio
         * @param weight defines the weight of the animation (default is -1 so no weight)
         * @returns a boolean indicating if the animation is running
         */
        RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
            if (weight === void 0) { weight = -1.0; }
            var targetPropertyPath = this._animation.targetPropertyPath;
            if (!targetPropertyPath || targetPropertyPath.length < 1) {
                this._stopped = true;
                return false;
            }
            var returnValue = true;
            var keys = this._animation.getKeys();
            // Adding a start key at frame 0 if missing
            if (keys[0].frame !== 0) {
                var newKey = { frame: 0, value: keys[0].value };
                keys.splice(0, 0, newKey);
            }
            // Adding a duplicate key when there is only one key at frame zero
            else if (keys.length === 1) {
                var newKey = { frame: 0.001, value: keys[0].value };
                keys.push(newKey);
            }
            // Check limits
            if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
                from = keys[0].frame;
            }
            if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
                to = keys[keys.length - 1].frame;
            }
            //to and from cannot be the same key
            if (from === to) {
                if (from > keys[0].frame) {
                    from--;
                }
                else if (to < keys[keys.length - 1].frame) {
                    to++;
                }
            }
            // Compute ratio
            var range = to - from;
            var offsetValue;
            // ratio represents the frame delta between from and to
            var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
            var highLimitValue = 0;
            this._previousDelay = delay;
            this._previousRatio = ratio;
            if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
                returnValue = false;
                highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
            }
            else {
                // Get max value if required
                if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
                    var keyOffset = to.toString() + from.toString();
                    if (!this._offsetsCache[keyOffset]) {
                        var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
                        var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
                        switch (this._animation.dataType) {
                            // Float
                            case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
                                this._offsetsCache[keyOffset] = toValue - fromValue;
                                break;
                            // Quaternion
                            case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                                break;
                            // Vector3
                            case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            // Vector2
                            case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            // Size
                            case BABYLON.Animation.ANIMATIONTYPE_SIZE:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            // Color3
                            case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
                                this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
                            default:
                                break;
                        }
                        this._highLimitsCache[keyOffset] = toValue;
                    }
                    highLimitValue = this._highLimitsCache[keyOffset];
                    offsetValue = this._offsetsCache[keyOffset];
                }
            }
            if (offsetValue === undefined) {
                switch (this._animation.dataType) {
                    // Float
                    case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
                        offsetValue = 0;
                        break;
                    // Quaternion
                    case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
                        offsetValue = _staticOffsetValueQuaternion;
                        break;
                    // Vector3
                    case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
                        offsetValue = _staticOffsetValueVector3;
                        break;
                    // Vector2
                    case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
                        offsetValue = _staticOffsetValueVector2;
                        break;
                    // Size
                    case BABYLON.Animation.ANIMATIONTYPE_SIZE:
                        offsetValue = _staticOffsetValueSize;
                        break;
                    // Color3
                    case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
                        offsetValue = _staticOffsetValueColor3;
                }
            }
            // Compute value
            var repeatCount = (ratio / range) >> 0;
            var currentFrame = returnValue ? from + ratio % range : to;
            // Need to normalize?
            if (this._host && this._host.syncRoot) {
                var syncRoot = this._host.syncRoot;
                var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
                currentFrame = from + (to - from) * hostNormalizedFrame;
            }
            // Reset events if looping
            var events = this._events;
            if (range > 0 && this.currentFrame > currentFrame ||
                range < 0 && this.currentFrame < currentFrame) {
                // Need to reset animation events
                for (var index = 0; index < events.length; index++) {
                    if (!events[index].onlyOnce) {
                        // reset event, the animation is looping
                        events[index].isDone = false;
                    }
                }
            }
            var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
            // Set value
            this.setValue(currentValue, weight);
            // Check events
            for (var index = 0; index < events.length; index++) {
                // Make sure current frame has passed event frame and that event frame is within the current range
                // Also, handle both forward and reverse animations
                if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
                    (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
                    var event = events[index];
                    if (!event.isDone) {
                        // If event should be done only once, remove it.
                        if (event.onlyOnce) {
                            events.splice(index, 1);
                            index--;
                        }
                        event.isDone = true;
                        event.action(currentFrame);
                    } // Don't do anything if the event has already be done.
                }
            }
            if (!returnValue) {
                this._stopped = true;
            }
            return returnValue;
        };
        return RuntimeAnimation;
    }());
    BABYLON.RuntimeAnimation = RuntimeAnimation;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.runtimeAnimation.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store an actual running animation
     */
    var Animatable = /** @class */ (function () {
        /**
         * Creates a new Animatable
         * @param scene defines the hosting scene
         * @param target defines the target object
         * @param fromFrame defines the starting frame number (default is 0)
         * @param toFrame defines the ending frame number (default is 100)
         * @param loopAnimation defines if the animation must loop (default is false)
         * @param speedRatio defines the factor to apply to animation speed (default is 1)
         * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
         * @param animations defines a group of animation to add to the new Animatable
         */
        function Animatable(scene, 
        /** defines the target object */
        target, 
        /** defines the starting frame number (default is 0) */
        fromFrame, 
        /** defines the ending frame number (default is 100) */
        toFrame, 
        /** defines if the animation must loop (default is false)  */
        loopAnimation, speedRatio, 
        /** defines a callback to call when animation ends if it is not looping */
        onAnimationEnd, animations) {
            if (fromFrame === void 0) { fromFrame = 0; }
            if (toFrame === void 0) { toFrame = 100; }
            if (loopAnimation === void 0) { loopAnimation = false; }
            if (speedRatio === void 0) { speedRatio = 1.0; }
            this.target = target;
            this.fromFrame = fromFrame;
            this.toFrame = toFrame;
            this.loopAnimation = loopAnimation;
            this.onAnimationEnd = onAnimationEnd;
            this._localDelayOffset = null;
            this._pausedDelay = null;
            this._runtimeAnimations = new Array();
            this._paused = false;
            this._speedRatio = 1;
            this._weight = -1.0;
            /**
             * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
             * This will only apply for non looping animation (default is true)
             */
            this.disposeOnEnd = true;
            /**
             * Gets a boolean indicating if the animation has started
             */
            this.animationStarted = false;
            /**
             * Observer raised when the animation ends
             */
            this.onAnimationEndObservable = new BABYLON.Observable();
            this._scene = scene;
            if (animations) {
                this.appendAnimations(target, animations);
            }
            this._speedRatio = speedRatio;
            scene._activeAnimatables.push(this);
        }
        Object.defineProperty(Animatable.prototype, "syncRoot", {
            /**
             * Gets the root Animatable used to synchronize and normalize animations
             */
            get: function () {
                return this._syncRoot;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animatable.prototype, "masterFrame", {
            /**
             * Gets the current frame of the first RuntimeAnimation
             * Used to synchronize Animatables
             */
            get: function () {
                if (this._runtimeAnimations.length === 0) {
                    return 0;
                }
                return this._runtimeAnimations[0].currentFrame;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animatable.prototype, "weight", {
            /**
             * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
             */
            get: function () {
                return this._weight;
            },
            set: function (value) {
                if (value === -1) { // -1 is ok and means no weight
                    this._weight = -1;
                    return;
                }
                // Else weight must be in [0, 1] range
                this._weight = Math.min(Math.max(value, 0), 1.0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Animatable.prototype, "speedRatio", {
            /**
             * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
             */
            get: function () {
                return this._speedRatio;
            },
            set: function (value) {
                for (var index = 0; index < this._runtimeAnimations.length; index++) {
                    var animation = this._runtimeAnimations[index];
                    animation._prepareForSpeedRatioChange(value);
                }
                this._speedRatio = value;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * Synchronize and normalize current Animatable with a source Animatable
         * This is useful when using animation weights and when animations are not of the same length
         * @param root defines the root Animatable to synchronize with
         * @returns the current Animatable
         */
        Animatable.prototype.syncWith = function (root) {
            this._syncRoot = root;
            if (root) {
                // Make sure this animatable will animate after the root
                var index = this._scene._activeAnimatables.indexOf(this);
                if (index > -1) {
                    this._scene._activeAnimatables.splice(index, 1);
                    this._scene._activeAnimatables.push(this);
                }
            }
            return this;
        };
        /**
         * Gets the list of runtime animations
         * @returns an array of RuntimeAnimation
         */
        Animatable.prototype.getAnimations = function () {
            return this._runtimeAnimations;
        };
        /**
         * Adds more animations to the current animatable
         * @param target defines the target of the animations
         * @param animations defines the new animations to add
         */
        Animatable.prototype.appendAnimations = function (target, animations) {
            for (var index = 0; index < animations.length; index++) {
                var animation = animations[index];
                this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
            }
        };
        /**
         * Gets the source animation for a specific property
         * @param property defines the propertyu to look for
         * @returns null or the source animation for the given property
         */
        Animatable.prototype.getAnimationByTargetProperty = function (property) {
            var runtimeAnimations = this._runtimeAnimations;
            for (var index = 0; index < runtimeAnimations.length; index++) {
                if (runtimeAnimations[index].animation.targetProperty === property) {
                    return runtimeAnimations[index].animation;
                }
            }
            return null;
        };
        /**
         * Gets the runtime animation for a specific property
         * @param property defines the propertyu to look for
         * @returns null or the runtime animation for the given property
         */
        Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
            var runtimeAnimations = this._runtimeAnimations;
            for (var index = 0; index < runtimeAnimations.length; index++) {
                if (runtimeAnimations[index].animation.targetProperty === property) {
                    return runtimeAnimations[index];
                }
            }
            return null;
        };
        /**
         * Resets the animatable to its original state
         */
        Animatable.prototype.reset = function () {
            var runtimeAnimations = this._runtimeAnimations;
            for (var index = 0; index < runtimeAnimations.length; index++) {
                runtimeAnimations[index].reset(true);
            }
            this._localDelayOffset = null;
            this._pausedDelay = null;
        };
        /**
         * Allows the animatable to blend with current running animations
         * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
         * @param blendingSpeed defines the blending speed to use
         */
        Animatable.prototype.enableBlending = function (blendingSpeed) {
            var runtimeAnimations = this._runtimeAnimations;
            for (var index = 0; index < runtimeAnimations.length; index++) {
                runtimeAnimations[index].animation.enableBlending = true;
                runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
            }
        };
        /**
         * Disable animation blending
         * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
         */
        Animatable.prototype.disableBlending = function () {
            var runtimeAnimations = this._runtimeAnimations;
            for (var index = 0; index < runtimeAnimations.length; index++) {
                runtimeAnimations[index].animation.enableBlending = false;
            }
        };
        /**
         * Jump directly to a given frame
         * @param frame defines the frame to jump to
         */
        Animatable.prototype.goToFrame = function (frame) {
            var runtimeAnimations = this._runtimeAnimations;
            if (runtimeAnimations[0]) {
                var fps = runtimeAnimations[0].animation.framePerSecond;
                var currentFrame = runtimeAnimations[0].currentFrame;
                var adjustTime = frame - currentFrame;
                var delay = adjustTime * 1000 / (fps * this.speedRatio);
                if (this._localDelayOffset === null) {
                    this._localDelayOffset = 0;
                }
                this._localDelayOffset -= delay;
            }
            for (var index = 0; index < runtimeAnimations.length; index++) {
                runtimeAnimations[index].goToFrame(frame);
            }
        };
        /**
         * Pause the animation
         */
        Animatable.prototype.pause = function () {
            if (this._paused) {
                return;
            }
            this._paused = true;
        };
        /**
         * Restart the animation
         */
        Animatable.prototype.restart = function () {
            this._paused = false;
        };
        Animatable.prototype._raiseOnAnimationEnd = function () {
            if (this.onAnimationEnd) {
                this.onAnimationEnd();
            }
            this.onAnimationEndObservable.notifyObservers(this);
        };
        /**
         * Stop and delete the current animation
         * @param animationName defines a string used to only stop some of the runtime animations instead of all
         * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty)
         */
        Animatable.prototype.stop = function (animationName, targetMask) {
            if (animationName || targetMask) {
                var idx = this._scene._activeAnimatables.indexOf(this);
                if (idx > -1) {
                    var runtimeAnimations = this._runtimeAnimations;
                    for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
                        var runtimeAnimation = runtimeAnimations[index];
                        if (animationName && runtimeAnimation.animation.name != animationName) {
                            continue;
                        }
                        if (targetMask && !targetMask(runtimeAnimation.target)) {
                            continue;
                        }
                        runtimeAnimation.dispose();
                        runtimeAnimations.splice(index, 1);
                    }
                    if (runtimeAnimations.length == 0) {
                        this._scene._activeAnimatables.splice(idx, 1);
                        this._raiseOnAnimationEnd();
                    }
                }
            }
            else {
                var index = this._scene._activeAnimatables.indexOf(this);
                if (index > -1) {
                    this._scene._activeAnimatables.splice(index, 1);
                    var runtimeAnimations = this._runtimeAnimations;
                    for (var index = 0; index < runtimeAnimations.length; index++) {
                        runtimeAnimations[index].dispose();
                    }
                    this._raiseOnAnimationEnd();
                }
            }
        };
        /**
         * Wait asynchronously for the animation to end
         * @returns a promise which will be fullfilled when the animation ends
         */
        Animatable.prototype.waitAsync = function () {
            var _this = this;
            return new Promise(function (resolve, reject) {
                _this.onAnimationEndObservable.add(function () {
                    resolve(_this);
                }, undefined, undefined, _this, true);
            });
        };
        /** @hidden */
        Animatable.prototype._animate = function (delay) {
            if (this._paused) {
                this.animationStarted = false;
                if (this._pausedDelay === null) {
                    this._pausedDelay = delay;
                }
                return true;
            }
            if (this._localDelayOffset === null) {
                this._localDelayOffset = delay;
                this._pausedDelay = null;
            }
            else if (this._pausedDelay !== null) {
                this._localDelayOffset += delay - this._pausedDelay;
                this._pausedDelay = null;
            }
            if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
                return true;
            }
            // Animating
            var running = false;
            var runtimeAnimations = this._runtimeAnimations;
            var index;
            for (index = 0; index < runtimeAnimations.length; index++) {
                var animation = runtimeAnimations[index];
                var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
                running = running || isRunning;
            }
            this.animationStarted = running;
            if (!running) {
                if (this.disposeOnEnd) {
                    // Remove from active animatables
                    index = this._scene._activeAnimatables.indexOf(this);
                    this._scene._activeAnimatables.splice(index, 1);
                    // Dispose all runtime animations
                    for (index = 0; index < runtimeAnimations.length; index++) {
                        runtimeAnimations[index].dispose();
                    }
                }
                this._raiseOnAnimationEnd();
                if (this.disposeOnEnd) {
                    this.onAnimationEnd = null;
                    this.onAnimationEndObservable.clear();
                }
            }
            return running;
        };
        return Animatable;
    }());
    BABYLON.Animatable = Animatable;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.animatable.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Base class used for every default easing function.
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var EasingFunction = /** @class */ (function () {
        function EasingFunction() {
            this._easingMode = EasingFunction.EASINGMODE_EASEIN;
        }
        /**
         * Sets the easing mode of the current function.
         * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
         */
        EasingFunction.prototype.setEasingMode = function (easingMode) {
            var n = Math.min(Math.max(easingMode, 0), 2);
            this._easingMode = n;
        };
        /**
         * Gets the current easing mode.
         * @returns the easing mode
         */
        EasingFunction.prototype.getEasingMode = function () {
            return this._easingMode;
        };
        /**
         * @hidden
         */
        EasingFunction.prototype.easeInCore = function (gradient) {
            throw new Error('You must implement this method');
        };
        /**
         * Given an input gradient between 0 and 1, this returns the corrseponding value
         * of the easing function.
         * @param gradient Defines the value between 0 and 1 we want the easing value for
         * @returns the corresponding value on the curve defined by the easing function
         */
        EasingFunction.prototype.ease = function (gradient) {
            switch (this._easingMode) {
                case EasingFunction.EASINGMODE_EASEIN:
                    return this.easeInCore(gradient);
                case EasingFunction.EASINGMODE_EASEOUT:
                    return (1 - this.easeInCore(1 - gradient));
            }
            if (gradient >= 0.5) {
                return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
            }
            return (this.easeInCore(gradient * 2) * 0.5);
        };
        /**
         * Interpolation follows the mathematical formula associated with the easing function.
         */
        EasingFunction.EASINGMODE_EASEIN = 0;
        /**
         * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
         */
        EasingFunction.EASINGMODE_EASEOUT = 1;
        /**
         * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
         */
        EasingFunction.EASINGMODE_EASEINOUT = 2;
        return EasingFunction;
    }());
    BABYLON.EasingFunction = EasingFunction;
    /**
     * Easing function with a circle shape (see link below).
     * @see https://easings.net/#easeInCirc
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var CircleEase = /** @class */ (function (_super) {
        __extends(CircleEase, _super);
        function CircleEase() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /** @hidden */
        CircleEase.prototype.easeInCore = function (gradient) {
            gradient = Math.max(0, Math.min(1, gradient));
            return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
        };
        return CircleEase;
    }(EasingFunction));
    BABYLON.CircleEase = CircleEase;
    /**
     * Easing function with a ease back shape (see link below).
     * @see https://easings.net/#easeInBack
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var BackEase = /** @class */ (function (_super) {
        __extends(BackEase, _super);
        /**
         * Instantiates a back ease easing
         * @see https://easings.net/#easeInBack
         * @param amplitude Defines the amplitude of the function
         */
        function BackEase(
        /** Defines the amplitude of the function */
        amplitude) {
            if (amplitude === void 0) { amplitude = 1; }
            var _this = _super.call(this) || this;
            _this.amplitude = amplitude;
            return _this;
        }
        /** @hidden */
        BackEase.prototype.easeInCore = function (gradient) {
            var num = Math.max(0, this.amplitude);
            return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
        };
        return BackEase;
    }(EasingFunction));
    BABYLON.BackEase = BackEase;
    /**
     * Easing function with a bouncing shape (see link below).
     * @see https://easings.net/#easeInBounce
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var BounceEase = /** @class */ (function (_super) {
        __extends(BounceEase, _super);
        /**
         * Instantiates a bounce easing
         * @see https://easings.net/#easeInBounce
         * @param bounces Defines the number of bounces
         * @param bounciness Defines the amplitude of the bounce
         */
        function BounceEase(
        /** Defines the number of bounces */
        bounces, 
        /** Defines the amplitude of the bounce */
        bounciness) {
            if (bounces === void 0) { bounces = 3; }
            if (bounciness === void 0) { bounciness = 2; }
            var _this = _super.call(this) || this;
            _this.bounces = bounces;
            _this.bounciness = bounciness;
            return _this;
        }
        /** @hidden */
        BounceEase.prototype.easeInCore = function (gradient) {
            var y = Math.max(0.0, this.bounces);
            var bounciness = this.bounciness;
            if (bounciness <= 1.0) {
                bounciness = 1.001;
            }
            var num9 = Math.pow(bounciness, y);
            var num5 = 1.0 - bounciness;
            var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
            var num15 = gradient * num4;
            var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
            var num3 = Math.floor(num65);
            var num13 = num3 + 1.0;
            var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
            var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
            var num7 = (num8 + num12) * 0.5;
            var num6 = gradient - num7;
            var num2 = num7 - num8;
            return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
        };
        return BounceEase;
    }(EasingFunction));
    BABYLON.BounceEase = BounceEase;
    /**
     * Easing function with a power of 3 shape (see link below).
     * @see https://easings.net/#easeInCubic
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var CubicEase = /** @class */ (function (_super) {
        __extends(CubicEase, _super);
        function CubicEase() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /** @hidden */
        CubicEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient * gradient);
        };
        return CubicEase;
    }(EasingFunction));
    BABYLON.CubicEase = CubicEase;
    /**
     * Easing function with an elastic shape (see link below).
     * @see https://easings.net/#easeInElastic
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var ElasticEase = /** @class */ (function (_super) {
        __extends(ElasticEase, _super);
        /**
         * Instantiates an elastic easing function
         * @see https://easings.net/#easeInElastic
         * @param oscillations Defines the number of oscillations
         * @param springiness Defines the amplitude of the oscillations
         */
        function ElasticEase(
        /** Defines the number of oscillations*/
        oscillations, 
        /** Defines the amplitude of the oscillations*/
        springiness) {
            if (oscillations === void 0) { oscillations = 3; }
            if (springiness === void 0) { springiness = 3; }
            var _this = _super.call(this) || this;
            _this.oscillations = oscillations;
            _this.springiness = springiness;
            return _this;
        }
        /** @hidden */
        ElasticEase.prototype.easeInCore = function (gradient) {
            var num2;
            var num3 = Math.max(0.0, this.oscillations);
            var num = Math.max(0.0, this.springiness);
            if (num == 0) {
                num2 = gradient;
            }
            else {
                num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
            }
            return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
        };
        return ElasticEase;
    }(EasingFunction));
    BABYLON.ElasticEase = ElasticEase;
    /**
     * Easing function with an exponential shape (see link below).
     * @see https://easings.net/#easeInExpo
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var ExponentialEase = /** @class */ (function (_super) {
        __extends(ExponentialEase, _super);
        /**
         * Instantiates an exponential easing function
         * @see https://easings.net/#easeInExpo
         * @param exponent Defines the exponent of the function
         */
        function ExponentialEase(
        /** Defines the exponent of the function */
        exponent) {
            if (exponent === void 0) { exponent = 2; }
            var _this = _super.call(this) || this;
            _this.exponent = exponent;
            return _this;
        }
        /** @hidden */
        ExponentialEase.prototype.easeInCore = function (gradient) {
            if (this.exponent <= 0) {
                return gradient;
            }
            return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
        };
        return ExponentialEase;
    }(EasingFunction));
    BABYLON.ExponentialEase = ExponentialEase;
    /**
     * Easing function with a power shape (see link below).
     * @see https://easings.net/#easeInQuad
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var PowerEase = /** @class */ (function (_super) {
        __extends(PowerEase, _super);
        /**
         * Instantiates an power base easing function
         * @see https://easings.net/#easeInQuad
         * @param power Defines the power of the function
         */
        function PowerEase(
        /** Defines the power of the function */
        power) {
            if (power === void 0) { power = 2; }
            var _this = _super.call(this) || this;
            _this.power = power;
            return _this;
        }
        /** @hidden */
        PowerEase.prototype.easeInCore = function (gradient) {
            var y = Math.max(0.0, this.power);
            return Math.pow(gradient, y);
        };
        return PowerEase;
    }(EasingFunction));
    BABYLON.PowerEase = PowerEase;
    /**
     * Easing function with a power of 2 shape (see link below).
     * @see https://easings.net/#easeInQuad
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var QuadraticEase = /** @class */ (function (_super) {
        __extends(QuadraticEase, _super);
        function QuadraticEase() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /** @hidden */
        QuadraticEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient);
        };
        return QuadraticEase;
    }(EasingFunction));
    BABYLON.QuadraticEase = QuadraticEase;
    /**
     * Easing function with a power of 4 shape (see link below).
     * @see https://easings.net/#easeInQuart
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var QuarticEase = /** @class */ (function (_super) {
        __extends(QuarticEase, _super);
        function QuarticEase() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /** @hidden */
        QuarticEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient * gradient * gradient);
        };
        return QuarticEase;
    }(EasingFunction));
    BABYLON.QuarticEase = QuarticEase;
    /**
     * Easing function with a power of 5 shape (see link below).
     * @see https://easings.net/#easeInQuint
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var QuinticEase = /** @class */ (function (_super) {
        __extends(QuinticEase, _super);
        function QuinticEase() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /** @hidden */
        QuinticEase.prototype.easeInCore = function (gradient) {
            return (gradient * gradient * gradient * gradient * gradient);
        };
        return QuinticEase;
    }(EasingFunction));
    BABYLON.QuinticEase = QuinticEase;
    /**
     * Easing function with a sin shape (see link below).
     * @see https://easings.net/#easeInSine
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var SineEase = /** @class */ (function (_super) {
        __extends(SineEase, _super);
        function SineEase() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /** @hidden */
        SineEase.prototype.easeInCore = function (gradient) {
            return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
        };
        return SineEase;
    }(EasingFunction));
    BABYLON.SineEase = SineEase;
    /**
     * Easing function with a bezier shape (see link below).
     * @see http://cubic-bezier.com/#.17,.67,.83,.67
     * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
     */
    var BezierCurveEase = /** @class */ (function (_super) {
        __extends(BezierCurveEase, _super);
        /**
         * Instantiates a bezier function
         * @see http://cubic-bezier.com/#.17,.67,.83,.67
         * @param x1 Defines the x component of the start tangent in the bezier curve
         * @param y1 Defines the y component of the start tangent in the bezier curve
         * @param x2 Defines the x component of the end tangent in the bezier curve
         * @param y2 Defines the y component of the end tangent in the bezier curve
         */
        function BezierCurveEase(
        /** Defines the x component of the start tangent in the bezier curve */
        x1, 
        /** Defines the y component of the start tangent in the bezier curve */
        y1, 
        /** Defines the x component of the end tangent in the bezier curve */
        x2, 
        /** Defines the y component of the end tangent in the bezier curve */
        y2) {
            if (x1 === void 0) { x1 = 0; }
            if (y1 === void 0) { y1 = 0; }
            if (x2 === void 0) { x2 = 1; }
            if (y2 === void 0) { y2 = 1; }
            var _this = _super.call(this) || this;
            _this.x1 = x1;
            _this.y1 = y1;
            _this.x2 = x2;
            _this.y2 = y2;
            return _this;
        }
        /** @hidden */
        BezierCurveEase.prototype.easeInCore = function (gradient) {
            return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
        };
        return BezierCurveEase;
    }(EasingFunction));
    BABYLON.BezierCurveEase = BezierCurveEase;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.easing.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * A Condition applied to an Action
     */
    var Condition = /** @class */ (function () {
        /**
         * Creates a new Condition
         * @param actionManager the manager of the action the condition is applied to
         */
        function Condition(actionManager) {
            this._actionManager = actionManager;
        }
        /**
         * Check if the current condition is valid
         * @returns a boolean
         */
        Condition.prototype.isValid = function () {
            return true;
        };
        /**
         * Internal only
         * @hidden
         */
        Condition.prototype._getProperty = function (propertyPath) {
            return this._actionManager._getProperty(propertyPath);
        };
        /**
         * Internal only
         * @hidden
         */
        Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
            return this._actionManager._getEffectiveTarget(target, propertyPath);
        };
        /**
         * Serialize placeholder for child classes
         * @returns the serialized object
         */
        Condition.prototype.serialize = function () {
        };
        /**
         * Internal only
         * @hidden
         */
        Condition.prototype._serialize = function (serializedCondition) {
            return {
                type: 2,
                children: [],
                name: serializedCondition.name,
                properties: serializedCondition.properties
            };
        };
        return Condition;
    }());
    BABYLON.Condition = Condition;
    /**
     * Defines specific conditional operators as extensions of Condition
     */
    var ValueCondition = /** @class */ (function (_super) {
        __extends(ValueCondition, _super);
        /**
         * Creates a new ValueCondition
         * @param actionManager manager for the action the condition applies to
         * @param target for the action
         * @param propertyPath path to specify the property of the target the conditional operator uses
         * @param value the value compared by the conditional operator against the current value of the property
         * @param operator the conditional operator, default ValueCondition.IsEqual
         */
        function ValueCondition(actionManager, target, 
        /** path to specify the property of the target the conditional operator uses  */
        propertyPath, 
        /** the value compared by the conditional operator against the current value of the property */
        value, 
        /** the conditional operator, default ValueCondition.IsEqual */
        operator) {
            if (operator === void 0) { operator = ValueCondition.IsEqual; }
            var _this = _super.call(this, actionManager) || this;
            _this.propertyPath = propertyPath;
            _this.value = value;
            _this.operator = operator;
            _this._target = target;
            _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
            _this._property = _this._getProperty(_this.propertyPath);
            return _this;
        }
        Object.defineProperty(ValueCondition, "IsEqual", {
            /**
             * returns the number for IsEqual
             */
            get: function () {
                return ValueCondition._IsEqual;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ValueCondition, "IsDifferent", {
            /**
             * Returns the number for IsDifferent
             */
            get: function () {
                return ValueCondition._IsDifferent;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ValueCondition, "IsGreater", {
            /**
             * Returns the number for IsGreater
             */
            get: function () {
                return ValueCondition._IsGreater;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ValueCondition, "IsLesser", {
            /**
             * Returns the number for IsLesser
             */
            get: function () {
                return ValueCondition._IsLesser;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Compares the given value with the property value for the specified conditional operator
         * @returns the result of the comparison
         */
        ValueCondition.prototype.isValid = function () {
            switch (this.operator) {
                case ValueCondition.IsGreater:
                    return this._effectiveTarget[this._property] > this.value;
                case ValueCondition.IsLesser:
                    return this._effectiveTarget[this._property] < this.value;
                case ValueCondition.IsEqual:
                case ValueCondition.IsDifferent:
                    var check;
                    if (this.value.equals) {
                        check = this.value.equals(this._effectiveTarget[this._property]);
                    }
                    else {
                        check = this.value === this._effectiveTarget[this._property];
                    }
                    return this.operator === ValueCondition.IsEqual ? check : !check;
            }
            return false;
        };
        /**
         * Serialize the ValueCondition into a JSON compatible object
         * @returns serialization object
         */
        ValueCondition.prototype.serialize = function () {
            return this._serialize({
                name: "ValueCondition",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
                    { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
                ]
            });
        };
        /**
         * Gets the name of the conditional operator for the ValueCondition
         * @param operator the conditional operator
         * @returns the name
         */
        ValueCondition.GetOperatorName = function (operator) {
            switch (operator) {
                case ValueCondition._IsEqual: return "IsEqual";
                case ValueCondition._IsDifferent: return "IsDifferent";
                case ValueCondition._IsGreater: return "IsGreater";
                case ValueCondition._IsLesser: return "IsLesser";
                default: return "";
            }
        };
        /**
         * Internal only
         * @hidden
         */
        ValueCondition._IsEqual = 0;
        /**
         * Internal only
         * @hidden
         */
        ValueCondition._IsDifferent = 1;
        /**
         * Internal only
         * @hidden
         */
        ValueCondition._IsGreater = 2;
        /**
         * Internal only
         * @hidden
         */
        ValueCondition._IsLesser = 3;
        return ValueCondition;
    }(Condition));
    BABYLON.ValueCondition = ValueCondition;
    /**
     * Defines a predicate condition as an extension of Condition
     */
    var PredicateCondition = /** @class */ (function (_super) {
        __extends(PredicateCondition, _super);
        /**
         * Creates a new PredicateCondition
         * @param actionManager manager for the action the condition applies to
         * @param predicate defines the predicate function used to validate the condition
         */
        function PredicateCondition(actionManager, 
        /** defines the predicate function used to validate the condition */
        predicate) {
            var _this = _super.call(this, actionManager) || this;
            _this.predicate = predicate;
            return _this;
        }
        /**
         * @returns the validity of the predicate condition
         */
        PredicateCondition.prototype.isValid = function () {
            return this.predicate();
        };
        return PredicateCondition;
    }(Condition));
    BABYLON.PredicateCondition = PredicateCondition;
    /**
     * Defines a state condition as an extension of Condition
     */
    var StateCondition = /** @class */ (function (_super) {
        __extends(StateCondition, _super);
        /**
         * Creates a new StateCondition
         * @param actionManager manager for the action the condition applies to
         * @param target of the condition
         * @param value to compare with target state
         */
        function StateCondition(actionManager, target, 
        /** Value to compare with target state  */
        value) {
            var _this = _super.call(this, actionManager) || this;
            _this.value = value;
            _this._target = target;
            return _this;
        }
        /**
         * Gets a boolean indicating if the current condition is met
         * @returns the validity of the state
         */
        StateCondition.prototype.isValid = function () {
            return this._target.state === this.value;
        };
        /**
         * Serialize the StateCondition into a JSON compatible object
         * @returns serialization object
         */
        StateCondition.prototype.serialize = function () {
            return this._serialize({
                name: "StateCondition",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "value", value: this.value }
                ]
            });
        };
        return StateCondition;
    }(Condition));
    BABYLON.StateCondition = StateCondition;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.condition.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * The action to be carried out following a trigger
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
     */
    var Action = /** @class */ (function () {
        /**
         * Creates a new Action
         * @param triggerOptions the trigger, with or without parameters, for the action
         * @param condition an optional determinant of action
         */
        function Action(
        /** the trigger, with or without parameters, for the action */
        triggerOptions, condition) {
            this.triggerOptions = triggerOptions;
            /**
            * An event triggered prior to action being executed.
            */
            this.onBeforeExecuteObservable = new BABYLON.Observable();
            if (triggerOptions.parameter) {
                this.trigger = triggerOptions.trigger;
                this._triggerParameter = triggerOptions.parameter;
            }
            else if (triggerOptions.trigger) {
                this.trigger = triggerOptions.trigger;
            }
            else {
                this.trigger = triggerOptions;
            }
            this._nextActiveAction = this;
            this._condition = condition;
        }
        /**
         * Internal only
         * @hidden
         */
        Action.prototype._prepare = function () {
        };
        /**
         * Gets the trigger parameters
         * @returns the trigger parameters
         */
        Action.prototype.getTriggerParameter = function () {
            return this._triggerParameter;
        };
        /**
         * Internal only - executes current action event
         * @hidden
         */
        Action.prototype._executeCurrent = function (evt) {
            if (this._nextActiveAction._condition) {
                var condition = this._nextActiveAction._condition;
                var currentRenderId = this._actionManager.getScene().getRenderId();
                // We cache the current evaluation for the current frame
                if (condition._evaluationId === currentRenderId) {
                    if (!condition._currentResult) {
                        return;
                    }
                }
                else {
                    condition._evaluationId = currentRenderId;
                    if (!condition.isValid()) {
                        condition._currentResult = false;
                        return;
                    }
                    condition._currentResult = true;
                }
            }
            this.onBeforeExecuteObservable.notifyObservers(this);
            this._nextActiveAction.execute(evt);
            this.skipToNextActiveAction();
        };
        /**
         * Execute placeholder for child classes
         * @param evt optional action event
         */
        Action.prototype.execute = function (evt) {
        };
        /**
         * Skips to next active action
         */
        Action.prototype.skipToNextActiveAction = function () {
            if (this._nextActiveAction._child) {
                if (!this._nextActiveAction._child._actionManager) {
                    this._nextActiveAction._child._actionManager = this._actionManager;
                }
                this._nextActiveAction = this._nextActiveAction._child;
            }
            else {
                this._nextActiveAction = this;
            }
        };
        /**
         * Adds action to chain of actions, may be a DoNothingAction
         * @param action defines the next action to execute
         * @returns The action passed in
         * @see https://www.babylonjs-playground.com/#1T30HR#0
         */
        Action.prototype.then = function (action) {
            this._child = action;
            action._actionManager = this._actionManager;
            action._prepare();
            return action;
        };
        /**
         * Internal only
         * @hidden
         */
        Action.prototype._getProperty = function (propertyPath) {
            return this._actionManager._getProperty(propertyPath);
        };
        /**
         * Internal only
         * @hidden
         */
        Action.prototype._getEffectiveTarget = function (target, propertyPath) {
            return this._actionManager._getEffectiveTarget(target, propertyPath);
        };
        /**
         * Serialize placeholder for child classes
         * @param parent of child
         * @returns the serialized object
         */
        Action.prototype.serialize = function (parent) {
        };
        /**
         * Internal only called by serialize
         * @hidden
         */
        Action.prototype._serialize = function (serializedAction, parent) {
            var serializationObject = {
                type: 1,
                children: [],
                name: serializedAction.name,
                properties: serializedAction.properties || []
            };
            // Serialize child
            if (this._child) {
                this._child.serialize(serializationObject);
            }
            // Check if "this" has a condition
            if (this._condition) {
                var serializedCondition = this._condition.serialize();
                serializedCondition.children.push(serializationObject);
                if (parent) {
                    parent.children.push(serializedCondition);
                }
                return serializedCondition;
            }
            if (parent) {
                parent.children.push(serializationObject);
            }
            return serializationObject;
        };
        /**
         * Internal only
         * @hidden
         */
        Action._SerializeValueAsString = function (value) {
            if (typeof value === "number") {
                return value.toString();
            }
            if (typeof value === "boolean") {
                return value ? "true" : "false";
            }
            if (value instanceof BABYLON.Vector2) {
                return value.x + ", " + value.y;
            }
            if (value instanceof BABYLON.Vector3) {
                return value.x + ", " + value.y + ", " + value.z;
            }
            if (value instanceof BABYLON.Color3) {
                return value.r + ", " + value.g + ", " + value.b;
            }
            if (value instanceof BABYLON.Color4) {
                return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
            }
            return value; // string
        };
        /**
         * Internal only
         * @hidden
         */
        Action._GetTargetProperty = function (target) {
            return {
                name: "target",
                targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
                    : target instanceof BABYLON.Light ? "LightProperties"
                        : target instanceof BABYLON.Camera ? "CameraProperties"
                            : "SceneProperties",
                value: target instanceof BABYLON.Scene ? "Scene" : target.name
            };
        };
        return Action;
    }());
    BABYLON.Action = Action;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.action.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * ActionEvent is the event being sent when an action is triggered.
     */
    var ActionEvent = /** @class */ (function () {
        /**
         * Creates a new ActionEvent
         * @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
         * @param additionalData additional data for the event
         */
        function ActionEvent(
        /** The mesh or sprite that triggered the action */
        source, 
        /** The X mouse cursor position at the time of the event */
        pointerX, 
        /** The Y mouse cursor position at the time of the event */
        pointerY, 
        /** The mesh that is currently pointed at (can be null) */
        meshUnderPointer, 
        /** the original (browser) event that triggered the ActionEvent */
        sourceEvent, 
        /** additional data for the event */
        additionalData) {
            this.source = source;
            this.pointerX = pointerX;
            this.pointerY = pointerY;
            this.meshUnderPointer = meshUnderPointer;
            this.sourceEvent = sourceEvent;
            this.additionalData = additionalData;
        }
        /**
         * Helper function to auto-create an ActionEvent from a source mesh.
         * @param source The source mesh that triggered the event
         * @param evt The original (browser) event
         * @param additionalData additional data for the event
         * @returns the new ActionEvent
         */
        ActionEvent.CreateNew = function (source, evt, additionalData) {
            var scene = source.getScene();
            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
        };
        /**
         * Helper function to auto-create an ActionEvent from a source sprite
         * @param source The source sprite that triggered the event
         * @param scene Scene associated with the sprite
         * @param evt The original (browser) event
         * @param additionalData additional data for the event
         * @returns the new ActionEvent
         */
        ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
            return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
        };
        /**
         * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
         * @param scene the scene where the event occurred
         * @param evt The original (browser) event
         * @returns the new ActionEvent
         */
        ActionEvent.CreateNewFromScene = function (scene, evt) {
            return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
        };
        /**
         * Helper function to auto-create an ActionEvent from a primitive
         * @param prim defines the target primitive
         * @param pointerPos defines the pointer position
         * @param evt The original (browser) event
         * @param additionalData additional data for the event
         * @returns the new ActionEvent
         */
        ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
            return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
        };
        return ActionEvent;
    }());
    BABYLON.ActionEvent = ActionEvent;
    /**
     * Action Manager manages all events to be triggered on a given mesh or the global scene.
     * A single scene can have many Action Managers to handle predefined actions on specific meshes.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var ActionManager = /** @class */ (function () {
        /**
         * Creates a new action manager
         * @param scene defines the hosting scene
         */
        function ActionManager(scene) {
            // Members
            /** Gets the list of actions */
            this.actions = new Array();
            /** Gets the cursor to use when hovering items */
            this.hoverCursor = '';
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            scene.actionManagers.push(this);
        }
        // Methods
        /**
         * Releases all associated resources
         */
        ActionManager.prototype.dispose = function () {
            var index = this._scene.actionManagers.indexOf(this);
            for (var i = 0; i < this.actions.length; i++) {
                var action = this.actions[i];
                ActionManager.Triggers[action.trigger]--;
                if (ActionManager.Triggers[action.trigger] === 0) {
                    delete ActionManager.Triggers[action.trigger];
                }
            }
            if (index > -1) {
                this._scene.actionManagers.splice(index, 1);
            }
        };
        /**
         * Gets hosting scene
         * @returns the hosting scene
         */
        ActionManager.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Does this action manager handles actions of any of the given triggers
         * @param triggers defines the triggers to be tested
         * @return a boolean indicating whether one (or more) of the triggers is handled
         */
        ActionManager.prototype.hasSpecificTriggers = function (triggers) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (triggers.indexOf(action.trigger) > -1) {
                    return true;
                }
            }
            return false;
        };
        /**
         * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
         * speed.
         * @param triggerA defines the trigger to be tested
         * @param triggerB defines the trigger to be tested
         * @return a boolean indicating whether one (or more) of the triggers is handled
         */
        ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (triggerA == action.trigger || triggerB == action.trigger) {
                    return true;
                }
            }
            return false;
        };
        /**
         * Does this action manager handles actions of a given trigger
         * @param trigger defines the trigger to be tested
         * @param parameterPredicate defines an optional predicate to filter triggers by parameter
         * @return whether the trigger is handled
         */
        ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (action.trigger === trigger) {
                    if (parameterPredicate) {
                        if (parameterPredicate(action.getTriggerParameter())) {
                            return true;
                        }
                    }
                    else {
                        return true;
                    }
                }
            }
            return false;
        };
        Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
            /**
             * Does this action manager has pointer triggers
             */
            get: function () {
                for (var index = 0; index < this.actions.length; index++) {
                    var action = this.actions[index];
                    if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
            /**
             * Does this action manager has pick triggers
             */
            get: function () {
                for (var index = 0; index < this.actions.length; index++) {
                    var action = this.actions[index];
                    if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "HasTriggers", {
            /**
             * Does exist one action manager with at least one trigger
             **/
            get: function () {
                for (var t in ActionManager.Triggers) {
                    if (ActionManager.Triggers.hasOwnProperty(t)) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ActionManager, "HasPickTriggers", {
            /**
             * Does exist one action manager with at least one pick trigger
             **/
            get: function () {
                for (var t in ActionManager.Triggers) {
                    if (ActionManager.Triggers.hasOwnProperty(t)) {
                        var t_int = parseInt(t);
                        if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
                            return true;
                        }
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Does exist one action manager that handles actions of a given trigger
         * @param trigger defines the trigger to be tested
         * @return a boolean indicating whether the trigger is handeled by at least one action manager
        **/
        ActionManager.HasSpecificTrigger = function (trigger) {
            for (var t in ActionManager.Triggers) {
                if (ActionManager.Triggers.hasOwnProperty(t)) {
                    var t_int = parseInt(t);
                    if (t_int === trigger) {
                        return true;
                    }
                }
            }
            return false;
        };
        /**
         * Registers an action to this action manager
         * @param action defines the action to be registered
         * @return the action amended (prepared) after registration
         */
        ActionManager.prototype.registerAction = function (action) {
            if (action.trigger === ActionManager.OnEveryFrameTrigger) {
                if (this.getScene().actionManager !== this) {
                    BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
                    return null;
                }
            }
            this.actions.push(action);
            if (ActionManager.Triggers[action.trigger]) {
                ActionManager.Triggers[action.trigger]++;
            }
            else {
                ActionManager.Triggers[action.trigger] = 1;
            }
            action._actionManager = this;
            action._prepare();
            return action;
        };
        /**
         * Unregisters an action to this action manager
         * @param action defines the action to be unregistered
         * @return a boolean indicating whether the action has been unregistered
         */
        ActionManager.prototype.unregisterAction = function (action) {
            var index = this.actions.indexOf(action);
            if (index !== -1) {
                this.actions.splice(index, 1);
                ActionManager.Triggers[action.trigger] -= 1;
                if (ActionManager.Triggers[action.trigger] === 0) {
                    delete ActionManager.Triggers[action.trigger];
                }
                delete action._actionManager;
                return true;
            }
            return false;
        };
        /**
         * Process a specific trigger
         * @param trigger defines the trigger to process
         * @param evt defines the event details to be processed
         */
        ActionManager.prototype.processTrigger = function (trigger, evt) {
            for (var index = 0; index < this.actions.length; index++) {
                var action = this.actions[index];
                if (action.trigger === trigger) {
                    if (evt) {
                        if (trigger === ActionManager.OnKeyUpTrigger
                            || trigger === ActionManager.OnKeyDownTrigger) {
                            var parameter = action.getTriggerParameter();
                            if (parameter && parameter !== evt.sourceEvent.keyCode) {
                                if (!parameter.toLowerCase) {
                                    continue;
                                }
                                var lowerCase = parameter.toLowerCase();
                                if (lowerCase !== evt.sourceEvent.key) {
                                    var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
                                    var actualkey = String.fromCharCode(unicode).toLowerCase();
                                    if (actualkey !== lowerCase) {
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                    action._executeCurrent(evt);
                }
            }
        };
        /** @hidden */
        ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
            var properties = propertyPath.split(".");
            for (var index = 0; index < properties.length - 1; index++) {
                target = target[properties[index]];
            }
            return target;
        };
        /** @hidden */
        ActionManager.prototype._getProperty = function (propertyPath) {
            var properties = propertyPath.split(".");
            return properties[properties.length - 1];
        };
        /**
         * Serialize this manager to a JSON object
         * @param name defines the property name to store this manager
         * @returns a JSON representation of this manager
         */
        ActionManager.prototype.serialize = function (name) {
            var root = {
                children: new Array(),
                name: name,
                type: 3,
                properties: new Array() // Empty for root but required
            };
            for (var i = 0; i < this.actions.length; i++) {
                var triggerObject = {
                    type: 0,
                    children: new Array(),
                    name: ActionManager.GetTriggerName(this.actions[i].trigger),
                    properties: new Array()
                };
                var triggerOptions = this.actions[i].triggerOptions;
                if (triggerOptions && typeof triggerOptions !== "number") {
                    if (triggerOptions.parameter instanceof BABYLON.Node) {
                        triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
                    }
                    else {
                        var parameter = {};
                        BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
                        if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
                            parameter._meshId = triggerOptions.parameter.mesh.id;
                        }
                        triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
                    }
                }
                // Serialize child action, recursively
                this.actions[i].serialize(triggerObject);
                // Add serialized trigger
                root.children.push(triggerObject);
            }
            return root;
        };
        /**
         * Creates a new ActionManager from a JSON data
         * @param parsedActions defines the JSON data to read from
         * @param object defines the hosting mesh
         * @param scene defines the hosting scene
         */
        ActionManager.Parse = function (parsedActions, object, scene) {
            var actionManager = new ActionManager(scene);
            if (object === null) {
                scene.actionManager = actionManager;
            }
            else {
                object.actionManager = actionManager;
            }
            // instanciate a new object
            var instanciate = function (name, params) {
                // TODO: We will need to find a solution for the next line when using commonjs / es6 .
                var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
                newInstance.constructor.apply(newInstance, params);
                return newInstance;
            };
            var parseParameter = function (name, value, target, propertyPath) {
                if (propertyPath === null) {
                    // String, boolean or float
                    var floatValue = parseFloat(value);
                    if (value === "true" || value === "false") {
                        return value === "true";
                    }
                    else {
                        return isNaN(floatValue) ? value : floatValue;
                    }
                }
                var effectiveTarget = propertyPath.split(".");
                var values = value.split(",");
                // Get effective Target
                for (var i = 0; i < effectiveTarget.length; i++) {
                    target = target[effectiveTarget[i]];
                }
                // Return appropriate value with its type
                if (typeof (target) === "boolean") {
                    return values[0] === "true";
                }
                if (typeof (target) === "string") {
                    return values[0];
                }
                // Parameters with multiple values such as Vector3 etc.
                var split = new Array();
                for (var i = 0; i < values.length; i++) {
                    split.push(parseFloat(values[i]));
                }
                if (target instanceof BABYLON.Vector3) {
                    return BABYLON.Vector3.FromArray(split);
                }
                if (target instanceof BABYLON.Vector4) {
                    return BABYLON.Vector4.FromArray(split);
                }
                if (target instanceof BABYLON.Color3) {
                    return BABYLON.Color3.FromArray(split);
                }
                if (target instanceof BABYLON.Color4) {
                    return BABYLON.Color4.FromArray(split);
                }
                return parseFloat(values[0]);
            };
            // traverse graph per trigger
            var traverse = function (parsedAction, trigger, condition, action, combineArray) {
                if (combineArray === void 0) { combineArray = null; }
                if (parsedAction.detached) {
                    return;
                }
                var parameters = new Array();
                var target = null;
                var propertyPath = null;
                var combine = parsedAction.combine && parsedAction.combine.length > 0;
                // Parameters
                if (parsedAction.type === 2) {
                    parameters.push(actionManager);
                }
                else {
                    parameters.push(trigger);
                }
                if (combine) {
                    var actions = new Array();
                    for (var j = 0; j < parsedAction.combine.length; j++) {
                        traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
                    }
                    parameters.push(actions);
                }
                else {
                    for (var i = 0; i < parsedAction.properties.length; i++) {
                        var value = parsedAction.properties[i].value;
                        var name = parsedAction.properties[i].name;
                        var targetType = parsedAction.properties[i].targetType;
                        if (name === "target") {
                            if (targetType !== null && targetType === "SceneProperties") {
                                value = target = scene;
                            }
                            else {
                                value = target = scene.getNodeByName(value);
                            }
                        }
                        else if (name === "parent") {
                            value = scene.getNodeByName(value);
                        }
                        else if (name === "sound") {
                            // Can not externalize to component, so only checks for the presence off the API.
                            if (scene.getSoundByName) {
                                value = scene.getSoundByName(value);
                            }
                        }
                        else if (name !== "propertyPath") {
                            if (parsedAction.type === 2 && name === "operator") {
                                value = BABYLON.ValueCondition[value];
                            }
                            else {
                                value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
                            }
                        }
                        else {
                            propertyPath = value;
                        }
                        parameters.push(value);
                    }
                }
                if (combineArray === null) {
                    parameters.push(condition);
                }
                else {
                    parameters.push(null);
                }
                // If interpolate value action
                if (parsedAction.name === "InterpolateValueAction") {
                    var param = parameters[parameters.length - 2];
                    parameters[parameters.length - 1] = param;
                    parameters[parameters.length - 2] = condition;
                }
                // Action or condition(s) and not CombineAction
                var newAction = instanciate(parsedAction.name, parameters);
                if (newAction instanceof BABYLON.Condition && condition !== null) {
                    var nothing = new BABYLON.DoNothingAction(trigger, condition);
                    if (action) {
                        action.then(nothing);
                    }
                    else {
                        actionManager.registerAction(nothing);
                    }
                    action = nothing;
                }
                if (combineArray === null) {
                    if (newAction instanceof BABYLON.Condition) {
                        condition = newAction;
                        newAction = action;
                    }
                    else {
                        condition = null;
                        if (action) {
                            action.then(newAction);
                        }
                        else {
                            actionManager.registerAction(newAction);
                        }
                    }
                }
                else {
                    combineArray.push(newAction);
                }
                for (var i = 0; i < parsedAction.children.length; i++) {
                    traverse(parsedAction.children[i], trigger, condition, newAction, null);
                }
            };
            // triggers
            for (var i = 0; i < parsedActions.children.length; i++) {
                var triggerParams;
                var trigger = parsedActions.children[i];
                if (trigger.properties.length > 0) {
                    var param = trigger.properties[0].value;
                    var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
                    if (value._meshId) {
                        value.mesh = scene.getMeshByID(value._meshId);
                    }
                    triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
                }
                else {
                    triggerParams = ActionManager[trigger.name];
                }
                for (var j = 0; j < trigger.children.length; j++) {
                    if (!trigger.detached) {
                        traverse(trigger.children[j], triggerParams, null, null);
                    }
                }
            }
        };
        /**
         * Get a trigger name by index
         * @param trigger defines the trigger index
         * @returns a trigger name
         */
        ActionManager.GetTriggerName = function (trigger) {
            switch (trigger) {
                case 0: return "NothingTrigger";
                case 1: return "OnPickTrigger";
                case 2: return "OnLeftPickTrigger";
                case 3: return "OnRightPickTrigger";
                case 4: return "OnCenterPickTrigger";
                case 5: return "OnPickDownTrigger";
                case 6: return "OnPickUpTrigger";
                case 7: return "OnLongPressTrigger";
                case 8: return "OnPointerOverTrigger";
                case 9: return "OnPointerOutTrigger";
                case 10: return "OnEveryFrameTrigger";
                case 11: return "OnIntersectionEnterTrigger";
                case 12: return "OnIntersectionExitTrigger";
                case 13: return "OnKeyDownTrigger";
                case 14: return "OnKeyUpTrigger";
                case 15: return "OnPickOutTrigger";
                default: return "";
            }
        };
        /**
         * Nothing
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.NothingTrigger = 0;
        /**
         * On pick
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnPickTrigger = 1;
        /**
         * On left pick
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnLeftPickTrigger = 2;
        /**
         * On right pick
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnRightPickTrigger = 3;
        /**
         * On center pick
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnCenterPickTrigger = 4;
        /**
         * On pick down
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnPickDownTrigger = 5;
        /**
         * On double pick
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnDoublePickTrigger = 6;
        /**
         * On pick up
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnPickUpTrigger = 7;
        /**
         * On pick out.
         * This trigger will only be raised if you also declared a OnPickDown
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnPickOutTrigger = 16;
        /**
         * On long press
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnLongPressTrigger = 8;
        /**
         * On pointer over
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnPointerOverTrigger = 9;
        /**
         * On pointer out
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnPointerOutTrigger = 10;
        /**
         * On every frame
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnEveryFrameTrigger = 11;
        /**
         * On intersection enter
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnIntersectionEnterTrigger = 12;
        /**
         * On intersection exit
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnIntersectionExitTrigger = 13;
        /**
         * On key down
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnKeyDownTrigger = 14;
        /**
         * On key up
         * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
         */
        ActionManager.OnKeyUpTrigger = 15;
        /** Gets the list of active triggers */
        ActionManager.Triggers = {};
        return ActionManager;
    }());
    BABYLON.ActionManager = ActionManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.actionManager.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This defines an action responsible to change the value of a property
     * by interpolating between its current value and the newly set one once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var InterpolateValueAction = /** @class */ (function (_super) {
        __extends(InterpolateValueAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the object containing the value to interpolate
         * @param propertyPath defines the path to the property in the target object
         * @param value defines the target value at the end of the interpolation
         * @param duration deines the time it will take for the property to interpolate to the value.
         * @param condition defines the trigger related conditions
         * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
         * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
         */
        function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
            if (duration === void 0) { duration = 1000; }
            var _this = _super.call(this, triggerOptions, condition) || this;
            /**
             * Defines the time it will take for the property to interpolate to the value.
             */
            _this.duration = 1000;
            /**
             * Observable triggered once the interpolation animation has been done.
             */
            _this.onInterpolationDoneObservable = new BABYLON.Observable();
            _this.propertyPath = propertyPath;
            _this.value = value;
            _this.duration = duration;
            _this.stopOtherAnimations = stopOtherAnimations;
            _this.onInterpolationDone = onInterpolationDone;
            _this._target = _this._effectiveTarget = target;
            return _this;
        }
        /** @hidden */
        InterpolateValueAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        };
        /**
         * Execute the action starts the value interpolation.
         */
        InterpolateValueAction.prototype.execute = function () {
            var _this = this;
            var scene = this._actionManager.getScene();
            var keys = [
                {
                    frame: 0,
                    value: this._effectiveTarget[this._property]
                }, {
                    frame: 100,
                    value: this.value
                }
            ];
            var dataType;
            if (typeof this.value === "number") {
                dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
            }
            else if (this.value instanceof BABYLON.Color3) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
            }
            else if (this.value instanceof BABYLON.Vector3) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
            }
            else if (this.value instanceof BABYLON.Matrix) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
            }
            else if (this.value instanceof BABYLON.Quaternion) {
                dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
            }
            else {
                BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
                return;
            }
            var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            animation.setKeys(keys);
            if (this.stopOtherAnimations) {
                scene.stopAnimation(this._effectiveTarget);
            }
            var wrapper = function () {
                _this.onInterpolationDoneObservable.notifyObservers(_this);
                if (_this.onInterpolationDone) {
                    _this.onInterpolationDone();
                }
            };
            scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        InterpolateValueAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "InterpolateValueAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
                    { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
                    { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
                ]
            }, parent);
        };
        return InterpolateValueAction;
    }(BABYLON.Action));
    BABYLON.InterpolateValueAction = InterpolateValueAction;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.interpolateValueAction.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This defines an action responsible to toggle a boolean once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var SwitchBooleanAction = /** @class */ (function (_super) {
        __extends(SwitchBooleanAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the object containing the boolean
         * @param propertyPath defines the path to the boolean property in the target object
         * @param condition defines the trigger related conditions
         */
        function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.propertyPath = propertyPath;
            _this._target = _this._effectiveTarget = target;
            return _this;
        }
        /** @hidden */
        SwitchBooleanAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        };
        /**
         * Execute the action toggle the boolean value.
         */
        SwitchBooleanAction.prototype.execute = function () {
            this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        SwitchBooleanAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SwitchBooleanAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath }
                ]
            }, parent);
        };
        return SwitchBooleanAction;
    }(BABYLON.Action));
    BABYLON.SwitchBooleanAction = SwitchBooleanAction;
    /**
     * This defines an action responsible to set a the state field of the target
     *  to a desired value once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var SetStateAction = /** @class */ (function (_super) {
        __extends(SetStateAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the object containing the state property
         * @param value defines the value to store in the state field
         * @param condition defines the trigger related conditions
         */
        function SetStateAction(triggerOptions, target, value, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.value = value;
            _this._target = target;
            return _this;
        }
        /**
         * Execute the action and store the value on the target state property.
         */
        SetStateAction.prototype.execute = function () {
            this._target.state = this.value;
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        SetStateAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SetStateAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "value", value: this.value }
                ]
            }, parent);
        };
        return SetStateAction;
    }(BABYLON.Action));
    BABYLON.SetStateAction = SetStateAction;
    /**
     * This defines an action responsible to set a property of the target
     *  to a desired value once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var SetValueAction = /** @class */ (function (_super) {
        __extends(SetValueAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the object containing the property
         * @param propertyPath defines the path of the property to set in the target
         * @param value defines the value to set in the property
         * @param condition defines the trigger related conditions
         */
        function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.propertyPath = propertyPath;
            _this.value = value;
            _this._target = _this._effectiveTarget = target;
            return _this;
        }
        /** @hidden */
        SetValueAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
        };
        /**
         * Execute the action and set the targetted property to the desired value.
         */
        SetValueAction.prototype.execute = function () {
            this._effectiveTarget[this._property] = this.value;
            if (this._target.markAsDirty) {
                this._target.markAsDirty(this._property);
            }
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        SetValueAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SetValueAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
                ]
            }, parent);
        };
        return SetValueAction;
    }(BABYLON.Action));
    BABYLON.SetValueAction = SetValueAction;
    /**
     * This defines an action responsible to increment the target value
     *  to a desired value once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var IncrementValueAction = /** @class */ (function (_super) {
        __extends(IncrementValueAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the object containing the property
         * @param propertyPath defines the path of the property to increment in the target
         * @param value defines the value value we should increment the property by
         * @param condition defines the trigger related conditions
         */
        function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.propertyPath = propertyPath;
            _this.value = value;
            _this._target = _this._effectiveTarget = target;
            return _this;
        }
        /** @hidden */
        IncrementValueAction.prototype._prepare = function () {
            this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
            this._property = this._getProperty(this.propertyPath);
            if (typeof this._effectiveTarget[this._property] !== "number") {
                BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
            }
        };
        /**
         * Execute the action and increment the target of the value amount.
         */
        IncrementValueAction.prototype.execute = function () {
            this._effectiveTarget[this._property] += this.value;
            if (this._target.markAsDirty) {
                this._target.markAsDirty(this._property);
            }
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        IncrementValueAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "IncrementValueAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "propertyPath", value: this.propertyPath },
                    { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
                ]
            }, parent);
        };
        return IncrementValueAction;
    }(BABYLON.Action));
    BABYLON.IncrementValueAction = IncrementValueAction;
    /**
     * This defines an action responsible to start an animation once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var PlayAnimationAction = /** @class */ (function (_super) {
        __extends(PlayAnimationAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the target animation or animation name
         * @param from defines from where the animation should start (animation frame)
         * @param end defines where the animation should stop (animation frame)
         * @param loop defines if the animation should loop or stop after the first play
         * @param condition defines the trigger related conditions
         */
        function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.from = from;
            _this.to = to;
            _this.loop = loop;
            _this._target = target;
            return _this;
        }
        /** @hidden */
        PlayAnimationAction.prototype._prepare = function () {
        };
        /**
         * Execute the action and play the animation.
         */
        PlayAnimationAction.prototype.execute = function () {
            var scene = this._actionManager.getScene();
            scene.beginAnimation(this._target, this.from, this.to, this.loop);
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        PlayAnimationAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "PlayAnimationAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    { name: "from", value: String(this.from) },
                    { name: "to", value: String(this.to) },
                    { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
                ]
            }, parent);
        };
        return PlayAnimationAction;
    }(BABYLON.Action));
    BABYLON.PlayAnimationAction = PlayAnimationAction;
    /**
     * This defines an action responsible to stop an animation once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var StopAnimationAction = /** @class */ (function (_super) {
        __extends(StopAnimationAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the target animation or animation name
         * @param condition defines the trigger related conditions
         */
        function StopAnimationAction(triggerOptions, target, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this._target = target;
            return _this;
        }
        /** @hidden */
        StopAnimationAction.prototype._prepare = function () {
        };
        /**
         * Execute the action and stop the animation.
         */
        StopAnimationAction.prototype.execute = function () {
            var scene = this._actionManager.getScene();
            scene.stopAnimation(this._target);
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        StopAnimationAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "StopAnimationAction",
                properties: [BABYLON.Action._GetTargetProperty(this._target)]
            }, parent);
        };
        return StopAnimationAction;
    }(BABYLON.Action));
    BABYLON.StopAnimationAction = StopAnimationAction;
    /**
     * This defines an action responsible that does nothing once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var DoNothingAction = /** @class */ (function (_super) {
        __extends(DoNothingAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param condition defines the trigger related conditions
         */
        function DoNothingAction(triggerOptions, condition) {
            if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
            return _super.call(this, triggerOptions, condition) || this;
        }
        /**
         * Execute the action and do nothing.
         */
        DoNothingAction.prototype.execute = function () {
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        DoNothingAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "DoNothingAction",
                properties: []
            }, parent);
        };
        return DoNothingAction;
    }(BABYLON.Action));
    BABYLON.DoNothingAction = DoNothingAction;
    /**
     * This defines an action responsible to trigger several actions once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var CombineAction = /** @class */ (function (_super) {
        __extends(CombineAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param children defines the list of aggregated animations to run
         * @param condition defines the trigger related conditions
         */
        function CombineAction(triggerOptions, children, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.children = children;
            return _this;
        }
        /** @hidden */
        CombineAction.prototype._prepare = function () {
            for (var index = 0; index < this.children.length; index++) {
                this.children[index]._actionManager = this._actionManager;
                this.children[index]._prepare();
            }
        };
        /**
         * Execute the action and executes all the aggregated actions.
         */
        CombineAction.prototype.execute = function (evt) {
            for (var index = 0; index < this.children.length; index++) {
                this.children[index].execute(evt);
            }
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        CombineAction.prototype.serialize = function (parent) {
            var serializationObject = _super.prototype._serialize.call(this, {
                name: "CombineAction",
                properties: [],
                combine: []
            }, parent);
            for (var i = 0; i < this.children.length; i++) {
                serializationObject.combine.push(this.children[i].serialize(null));
            }
            return serializationObject;
        };
        return CombineAction;
    }(BABYLON.Action));
    BABYLON.CombineAction = CombineAction;
    /**
     * This defines an action responsible to run code (external event) once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var ExecuteCodeAction = /** @class */ (function (_super) {
        __extends(ExecuteCodeAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param func defines the callback function to run
         * @param condition defines the trigger related conditions
         */
        function ExecuteCodeAction(triggerOptions, func, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this.func = func;
            return _this;
        }
        /**
         * Execute the action and run the attached code.
         */
        ExecuteCodeAction.prototype.execute = function (evt) {
            this.func(evt);
        };
        return ExecuteCodeAction;
    }(BABYLON.Action));
    BABYLON.ExecuteCodeAction = ExecuteCodeAction;
    /**
     * This defines an action responsible to set the parent property of the target once triggered.
     * @see http://doc.babylonjs.com/how_to/how_to_use_actions
     */
    var SetParentAction = /** @class */ (function (_super) {
        __extends(SetParentAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param target defines the target containing the parent property
         * @param parent defines from where the animation should start (animation frame)
         * @param condition defines the trigger related conditions
         */
        function SetParentAction(triggerOptions, target, parent, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this._target = target;
            _this._parent = parent;
            return _this;
        }
        /** @hidden */
        SetParentAction.prototype._prepare = function () {
        };
        /**
         * Execute the action and set the parent property.
         */
        SetParentAction.prototype.execute = function () {
            if (this._target.parent === this._parent) {
                return;
            }
            var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
            invertParentWorldMatrix.invert();
            this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
            this._target.parent = this._parent;
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        SetParentAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "SetParentAction",
                properties: [
                    BABYLON.Action._GetTargetProperty(this._target),
                    BABYLON.Action._GetTargetProperty(this._parent),
                ]
            }, parent);
        };
        return SetParentAction;
    }(BABYLON.Action));
    BABYLON.SetParentAction = SetParentAction;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.directActions.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to manage multiple sprites on the same spritesheet
     * @see http://doc.babylonjs.com/babylon101/sprites
     */
    var SpriteManager = /** @class */ (function () {
        /**
         * Creates a new sprite manager
         * @param name defines the manager's name
         * @param imgUrl defines the sprite sheet url
         * @param capacity defines the maximum allowed number of sprites
         * @param cellSize defines the size of a sprite cell
         * @param scene defines the hosting scene
         * @param epsilon defines the epsilon value to align texture (0.01 by default)
         * @param samplingMode defines the smapling mode to use with spritesheet
         */
        function SpriteManager(
        /** defines the manager's name */
        name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
            if (epsilon === void 0) { epsilon = 0.01; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            this.name = name;
            /** Gets the list of sprites */
            this.sprites = new Array();
            /** Gets or sets the rendering group id (0 by default) */
            this.renderingGroupId = 0;
            /** Gets or sets camera layer mask */
            this.layerMask = 0x0FFFFFFF;
            /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
            this.fogEnabled = true;
            /** Gets or sets a boolean indicating if the sprites are pickable */
            this.isPickable = false;
            /**
            * An event triggered when the manager is disposed.
            */
            this.onDisposeObservable = new BABYLON.Observable();
            this._vertexBuffers = {};
            if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
                scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
            }
            this._capacity = capacity;
            this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
            this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            if (cellSize.width && cellSize.height) {
                this.cellWidth = cellSize.width;
                this.cellHeight = cellSize.height;
            }
            else if (cellSize !== undefined) {
                this.cellWidth = cellSize;
                this.cellHeight = cellSize;
            }
            else {
                return;
            }
            this._epsilon = epsilon;
            this._scene = scene;
            this._scene.spriteManagers.push(this);
            var indices = [];
            var index = 0;
            for (var count = 0; count < capacity; count++) {
                indices.push(index);
                indices.push(index + 1);
                indices.push(index + 2);
                indices.push(index);
                indices.push(index + 2);
                indices.push(index + 3);
                index += 4;
            }
            this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
            // VBO
            // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
            this._vertexData = new Float32Array(capacity * 16 * 4);
            this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
            var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
            var options = this._buffer.createVertexBuffer("options", 4, 4);
            var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
            var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
            this._vertexBuffers["options"] = options;
            this._vertexBuffers["cellInfo"] = cellInfo;
            this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
            // Effects
            this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
            this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
        }
        Object.defineProperty(SpriteManager.prototype, "onDispose", {
            /**
             * Callback called when the manager is disposed
             */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SpriteManager.prototype, "texture", {
            /**
             * Gets or sets the spritesheet texture
             */
            get: function () {
                return this._spriteTexture;
            },
            set: function (value) {
                this._spriteTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
            var arrayOffset = index * 16;
            if (offsetX === 0) {
                offsetX = this._epsilon;
            }
            else if (offsetX === 1) {
                offsetX = 1 - this._epsilon;
            }
            if (offsetY === 0) {
                offsetY = this._epsilon;
            }
            else if (offsetY === 1) {
                offsetY = 1 - this._epsilon;
            }
            this._vertexData[arrayOffset] = sprite.position.x;
            this._vertexData[arrayOffset + 1] = sprite.position.y;
            this._vertexData[arrayOffset + 2] = sprite.position.z;
            this._vertexData[arrayOffset + 3] = sprite.angle;
            this._vertexData[arrayOffset + 4] = sprite.width;
            this._vertexData[arrayOffset + 5] = sprite.height;
            this._vertexData[arrayOffset + 6] = offsetX;
            this._vertexData[arrayOffset + 7] = offsetY;
            this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
            this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
            var offset = (sprite.cellIndex / rowSize) >> 0;
            this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
            this._vertexData[arrayOffset + 11] = offset;
            // Color
            this._vertexData[arrayOffset + 12] = sprite.color.r;
            this._vertexData[arrayOffset + 13] = sprite.color.g;
            this._vertexData[arrayOffset + 14] = sprite.color.b;
            this._vertexData[arrayOffset + 15] = sprite.color.a;
        };
        /**
         * Intersects the sprites with a ray
         * @param ray defines the ray to intersect with
         * @param camera defines the current active camera
         * @param predicate defines a predicate used to select candidate sprites
         * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
         * @returns null if no hit or a PickingInfo
         */
        SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
            var count = Math.min(this._capacity, this.sprites.length);
            var min = BABYLON.Vector3.Zero();
            var max = BABYLON.Vector3.Zero();
            var distance = Number.MAX_VALUE;
            var currentSprite = null;
            var cameraSpacePosition = BABYLON.Vector3.Zero();
            var cameraView = camera.getViewMatrix();
            for (var index = 0; index < count; index++) {
                var sprite = this.sprites[index];
                if (!sprite) {
                    continue;
                }
                if (predicate) {
                    if (!predicate(sprite)) {
                        continue;
                    }
                }
                else if (!sprite.isPickable) {
                    continue;
                }
                BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
                min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
                max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
                if (ray.intersectsBoxMinMax(min, max)) {
                    var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
                    if (distance > currentDistance) {
                        distance = currentDistance;
                        currentSprite = sprite;
                        if (fastCheck) {
                            break;
                        }
                    }
                }
            }
            if (currentSprite) {
                var result = new BABYLON.PickingInfo();
                result.hit = true;
                result.pickedSprite = currentSprite;
                result.distance = distance;
                return result;
            }
            return null;
        };
        /**
         * Render all child sprites
         */
        SpriteManager.prototype.render = function () {
            // Check
            if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady()) {
                return;
            }
            var engine = this._scene.getEngine();
            var baseSize = this._spriteTexture.getBaseSize();
            // Sprites
            var deltaTime = engine.getDeltaTime();
            var max = Math.min(this._capacity, this.sprites.length);
            var rowSize = baseSize.width / this.cellWidth;
            var offset = 0;
            for (var index = 0; index < max; index++) {
                var sprite = this.sprites[index];
                if (!sprite || !sprite.isVisible) {
                    continue;
                }
                sprite._animate(deltaTime);
                this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
                this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
                this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
                this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
            }
            this._buffer.update(this._vertexData);
            // Render
            var effect = this._effectBase;
            if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
                effect = this._effectFog;
            }
            engine.enableEffect(effect);
            var viewMatrix = this._scene.getViewMatrix();
            effect.setTexture("diffuseSampler", this._spriteTexture);
            effect.setMatrix("view", viewMatrix);
            effect.setMatrix("projection", this._scene.getProjectionMatrix());
            effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
            // Fog
            if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
                effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
                effect.setColor3("vFogColor", this._scene.fogColor);
            }
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
            // Draw order
            engine.setDepthFunctionToLessOrEqual();
            effect.setBool("alphaTest", true);
            engine.setColorWrite(false);
            engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
            engine.setColorWrite(true);
            effect.setBool("alphaTest", false);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
            engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
        };
        /**
         * Release associated resources
         */
        SpriteManager.prototype.dispose = function () {
            if (this._buffer) {
                this._buffer.dispose();
                this._buffer = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            if (this._spriteTexture) {
                this._spriteTexture.dispose();
                this._spriteTexture = null;
            }
            // Remove from scene
            var index = this._scene.spriteManagers.indexOf(this);
            this._scene.spriteManagers.splice(index, 1);
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        return SpriteManager;
    }());
    BABYLON.SpriteManager = SpriteManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.spriteManager.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to represent a sprite
     * @see http://doc.babylonjs.com/babylon101/sprites
     */
    var Sprite = /** @class */ (function () {
        /**
         * Creates a new Sprite
         * @param name defines the name
         * @param manager defines the manager
         */
        function Sprite(
        /** defines the name */
        name, manager) {
            this.name = name;
            /** Gets or sets the main color */
            this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            /** Gets or sets the width */
            this.width = 1.0;
            /** Gets or sets the height */
            this.height = 1.0;
            /** Gets or sets rotation angle */
            this.angle = 0;
            /** Gets or sets the cell index in the sprite sheet */
            this.cellIndex = 0;
            /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
            this.invertU = 0;
            /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
            this.invertV = 0;
            /** Gets the list of attached animations */
            this.animations = new Array();
            /** Gets or sets a boolean indicating if the sprite can be picked */
            this.isPickable = false;
            this._animationStarted = false;
            this._loopAnimation = false;
            this._fromIndex = 0;
            this._toIndex = 0;
            this._delay = 0;
            this._direction = 1;
            this._time = 0;
            /**
             * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
             */
            this.isVisible = true;
            this._manager = manager;
            this._manager.sprites.push(this);
            this.position = BABYLON.Vector3.Zero();
        }
        Object.defineProperty(Sprite.prototype, "size", {
            /**
             * Gets or sets the sprite size
             */
            get: function () {
                return this.width;
            },
            set: function (value) {
                this.width = value;
                this.height = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Starts an animation
         * @param from defines the initial key
         * @param to defines the end key
         * @param loop defines if the animation must loop
         * @param delay defines the start delay (in ms)
         * @param onAnimationEnd defines a callback to call when animation ends
         */
        Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
            this._fromIndex = from;
            this._toIndex = to;
            this._loopAnimation = loop;
            this._delay = delay;
            this._animationStarted = true;
            this._direction = from < to ? 1 : -1;
            this.cellIndex = from;
            this._time = 0;
            this._onAnimationEnd = onAnimationEnd;
        };
        /** Stops current animation (if any) */
        Sprite.prototype.stopAnimation = function () {
            this._animationStarted = false;
        };
        /** @hidden */
        Sprite.prototype._animate = function (deltaTime) {
            if (!this._animationStarted) {
                return;
            }
            this._time += deltaTime;
            if (this._time > this._delay) {
                this._time = this._time % this._delay;
                this.cellIndex += this._direction;
                if (this.cellIndex > this._toIndex) {
                    if (this._loopAnimation) {
                        this.cellIndex = this._fromIndex;
                    }
                    else {
                        this.cellIndex = this._toIndex;
                        this._animationStarted = false;
                        if (this._onAnimationEnd) {
                            this._onAnimationEnd();
                        }
                        if (this.disposeWhenFinishedAnimating) {
                            this.dispose();
                        }
                    }
                }
            }
        };
        /** Release associated resources */
        Sprite.prototype.dispose = function () {
            for (var i = 0; i < this._manager.sprites.length; i++) {
                if (this._manager.sprites[i] == this) {
                    this._manager.sprites.splice(i, 1);
                }
            }
        };
        return Sprite;
    }());
    BABYLON.Sprite = Sprite;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sprite.js.map

var BABYLON;
(function (BABYLON) {
    BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
        if (!BABYLON.PickingInfo) {
            return null;
        }
        var pickingInfo = null;
        if (!camera) {
            if (!this.activeCamera) {
                return null;
            }
            camera = this.activeCamera;
        }
        if (this.spriteManagers.length > 0) {
            for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
                var spriteManager = this.spriteManagers[spriteIndex];
                if (!spriteManager.isPickable) {
                    continue;
                }
                var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
                if (!result || !result.hit) {
                    continue;
                }
                if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
                    continue;
                }
                pickingInfo = result;
                if (fastCheck) {
                    break;
                }
            }
        }
        return pickingInfo || new BABYLON.PickingInfo();
    };
    BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
        this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
        return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
    };
    BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
        if (!this._tempSpritePickingRay) {
            return null;
        }
        if (!camera) {
            if (!this.activeCamera) {
                return null;
            }
            camera = this.activeCamera;
        }
        BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
        return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
    };
    BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
        if (this._pointerOverSprite === sprite) {
            return;
        }
        if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
            this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
        }
        this._pointerOverSprite = sprite;
        if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
            this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
        }
    };
    BABYLON.Scene.prototype.getPointerOverSprite = function () {
        return this._pointerOverSprite;
    };
    /**
     * Defines the sprite scene component responsible to manage sprites
     * in a given scene.
     */
    var SpriteSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function SpriteSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
            this.scene = scene;
            this.scene.spriteManagers = new Array();
            this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
            this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
            this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
            this._spritePredicate = function (sprite) {
                if (!sprite.actionManager) {
                    return false;
                }
                return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
            };
        }
        /**
         * Registers the component in a given scene
         */
        SpriteSceneComponent.prototype.register = function () {
            this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
            this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
            this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        SpriteSceneComponent.prototype.rebuild = function () {
            /** Nothing to do for sprites */
        };
        /**
         * Disposes the component and the associated ressources.
         */
        SpriteSceneComponent.prototype.dispose = function () {
            this.scene.onBeforeSpritesRenderingObservable.clear();
            this.scene.onAfterSpritesRenderingObservable.clear();
            var spriteManagers = this.scene.spriteManagers;
            while (spriteManagers.length) {
                spriteManagers[0].dispose();
            }
        };
        SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
            var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
            if (result) {
                result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
            }
            return result;
        };
        SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
            var scene = this.scene;
            if (isMeshPicked) {
                scene.setPointerOverSprite(null);
            }
            else {
                pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
                if (pickResult && pickResult.hit && pickResult.pickedSprite) {
                    scene.setPointerOverSprite(pickResult.pickedSprite);
                    if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
                        canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
                    }
                    else {
                        canvas.style.cursor = scene.hoverCursor;
                    }
                }
                else {
                    scene.setPointerOverSprite(null);
                }
            }
            return pickResult;
        };
        SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
            var scene = this.scene;
            scene._pickedDownSprite = null;
            if (scene.spriteManagers.length > 0) {
                pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
                if (pickResult && pickResult.hit && pickResult.pickedSprite) {
                    if (pickResult.pickedSprite.actionManager) {
                        scene._pickedDownSprite = pickResult.pickedSprite;
                        switch (evt.button) {
                            case 0:
                                pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
                                break;
                            case 1:
                                pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
                                break;
                            case 2:
                                pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
                                break;
                        }
                        if (pickResult.pickedSprite.actionManager) {
                            pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
                        }
                    }
                }
            }
            return pickResult;
        };
        SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
            var scene = this.scene;
            if (scene.spriteManagers.length > 0) {
                var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
                if (spritePickResult) {
                    if (spritePickResult.hit && spritePickResult.pickedSprite) {
                        if (spritePickResult.pickedSprite.actionManager) {
                            spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
                            if (spritePickResult.pickedSprite.actionManager) {
                                if (!this.scene._isPointerSwiping()) {
                                    spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
                                }
                            }
                        }
                    }
                    if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
                        scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
                    }
                }
            }
            return pickResult;
        };
        return SpriteSceneComponent;
    }());
    BABYLON.SpriteSceneComponent = SpriteSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.spriteSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     */
    var IntersectionInfo = /** @class */ (function () {
        function IntersectionInfo(bu, bv, distance) {
            this.bu = bu;
            this.bv = bv;
            this.distance = distance;
            this.faceId = 0;
            this.subMeshId = 0;
        }
        return IntersectionInfo;
    }());
    BABYLON.IntersectionInfo = IntersectionInfo;
    /**
     * Information about the result of picking within a scene
     * @see https://doc.babylonjs.com/babylon101/picking_collisions
     */
    var PickingInfo = /** @class */ (function () {
        function PickingInfo() {
            /**
             * If the pick collided with an object
             */
            this.hit = false;
            /**
             * Distance away where the pick collided
             */
            this.distance = 0;
            /**
             * The location of pick collision
             */
            this.pickedPoint = null;
            /**
             * The mesh corresponding the the pick collision
             */
            this.pickedMesh = null;
            /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
            this.bu = 0;
            /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
            this.bv = 0;
            /** The id of the face on the mesh that was picked  */
            this.faceId = -1;
            /** Id of the the submesh that was picked */
            this.subMeshId = 0;
            /** If a sprite was picked, this will be the sprite the pick collided with */
            this.pickedSprite = null;
            /**
             * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
             */
            this.originMesh = null;
            /**
             * The ray that was used to perform the picking.
             */
            this.ray = null;
        }
        /**
         * Gets the normal correspodning to the face the pick collided with
         * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
         * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
         * @returns The normal correspodning to the face the pick collided with
         */
        PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
            if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
            if (useVerticesNormals === void 0) { useVerticesNormals = true; }
            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                return null;
            }
            var indices = this.pickedMesh.getIndices();
            if (!indices) {
                return null;
            }
            var result;
            if (useVerticesNormals) {
                var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
                var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
                var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
                normal0 = normal0.scale(this.bu);
                normal1 = normal1.scale(this.bv);
                normal2 = normal2.scale(1.0 - this.bu - this.bv);
                result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
            }
            else {
                var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
                var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
                var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
                var p1p2 = vertex1.subtract(vertex2);
                var p3p2 = vertex3.subtract(vertex2);
                result = BABYLON.Vector3.Cross(p1p2, p3p2);
            }
            if (useWorldCoordinates) {
                var wm = this.pickedMesh.getWorldMatrix();
                if (this.pickedMesh.nonUniformScaling) {
                    BABYLON.Tmp.Matrix[0].copyFrom(wm);
                    wm = BABYLON.Tmp.Matrix[0];
                    wm.setTranslationFromFloats(0, 0, 0);
                    wm.invert();
                    wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
                    wm = BABYLON.Tmp.Matrix[1];
                }
                result = BABYLON.Vector3.TransformNormal(result, wm);
            }
            result.normalize();
            return result;
        };
        /**
         * Gets the texture coordinates of where the pick occured
         * @returns the vector containing the coordnates of the texture
         */
        PickingInfo.prototype.getTextureCoordinates = function () {
            if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                return null;
            }
            var indices = this.pickedMesh.getIndices();
            if (!indices) {
                return null;
            }
            var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            if (!uvs) {
                return null;
            }
            var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
            var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
            var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
            uv0 = uv0.scale(1.0 - this.bu - this.bv);
            uv1 = uv1.scale(this.bu);
            uv2 = uv2.scale(this.bv);
            return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
        };
        return PickingInfo;
    }());
    BABYLON.PickingInfo = PickingInfo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pickingInfo.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class representing a ray with position and direction
     */
    var Ray = /** @class */ (function () {
        /**
         * Creates a new ray
         * @param origin origin point
         * @param direction direction
         * @param length length of the ray
         */
        function Ray(
        /** origin point */
        origin, 
        /** direction */
        direction, 
        /** length of the ray */
        length) {
            if (length === void 0) { length = Number.MAX_VALUE; }
            this.origin = origin;
            this.direction = direction;
            this.length = length;
        }
        // Methods
        /**
         * Checks if the ray intersects a box
         * @param minimum bound of the box
         * @param maximum bound of the box
         * @returns if the box was hit
         */
        Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
            var d = 0.0;
            var maxValue = Number.MAX_VALUE;
            var inv;
            var min;
            var max;
            var temp;
            if (Math.abs(this.direction.x) < 0.0000001) {
                if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
                    return false;
                }
            }
            else {
                inv = 1.0 / this.direction.x;
                min = (minimum.x - this.origin.x) * inv;
                max = (maximum.x - this.origin.x) * inv;
                if (max === -Infinity) {
                    max = Infinity;
                }
                if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                d = Math.max(min, d);
                maxValue = Math.min(max, maxValue);
                if (d > maxValue) {
                    return false;
                }
            }
            if (Math.abs(this.direction.y) < 0.0000001) {
                if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
                    return false;
                }
            }
            else {
                inv = 1.0 / this.direction.y;
                min = (minimum.y - this.origin.y) * inv;
                max = (maximum.y - this.origin.y) * inv;
                if (max === -Infinity) {
                    max = Infinity;
                }
                if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                d = Math.max(min, d);
                maxValue = Math.min(max, maxValue);
                if (d > maxValue) {
                    return false;
                }
            }
            if (Math.abs(this.direction.z) < 0.0000001) {
                if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
                    return false;
                }
            }
            else {
                inv = 1.0 / this.direction.z;
                min = (minimum.z - this.origin.z) * inv;
                max = (maximum.z - this.origin.z) * inv;
                if (max === -Infinity) {
                    max = Infinity;
                }
                if (min > max) {
                    temp = min;
                    min = max;
                    max = temp;
                }
                d = Math.max(min, d);
                maxValue = Math.min(max, maxValue);
                if (d > maxValue) {
                    return false;
                }
            }
            return true;
        };
        /**
         * Checks if the ray intersects a box
         * @param box the bounding box to check
         * @returns if the box was hit
         */
        Ray.prototype.intersectsBox = function (box) {
            return this.intersectsBoxMinMax(box.minimum, box.maximum);
        };
        /**
         * If the ray hits a sphere
         * @param sphere the bounding sphere to check
         * @returns true if it hits the sphere
         */
        Ray.prototype.intersectsSphere = function (sphere) {
            var x = sphere.center.x - this.origin.x;
            var y = sphere.center.y - this.origin.y;
            var z = sphere.center.z - this.origin.z;
            var pyth = (x * x) + (y * y) + (z * z);
            var rr = sphere.radius * sphere.radius;
            if (pyth <= rr) {
                return true;
            }
            var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
            if (dot < 0.0) {
                return false;
            }
            var temp = pyth - (dot * dot);
            return temp <= rr;
        };
        /**
         * If the ray hits a triange
         * @param vertex0 triangle vertex
         * @param vertex1 triangle vertex
         * @param vertex2 triangle vertex
         * @returns intersection information if hit
         */
        Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
            if (!this._edge1) {
                this._edge1 = BABYLON.Vector3.Zero();
                this._edge2 = BABYLON.Vector3.Zero();
                this._pvec = BABYLON.Vector3.Zero();
                this._tvec = BABYLON.Vector3.Zero();
                this._qvec = BABYLON.Vector3.Zero();
            }
            vertex1.subtractToRef(vertex0, this._edge1);
            vertex2.subtractToRef(vertex0, this._edge2);
            BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
            var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
            if (det === 0) {
                return null;
            }
            var invdet = 1 / det;
            this.origin.subtractToRef(vertex0, this._tvec);
            var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
            if (bu < 0 || bu > 1.0) {
                return null;
            }
            BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
            var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
            if (bv < 0 || bu + bv > 1.0) {
                return null;
            }
            //check if the distance is longer than the predefined length.
            var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
            if (distance > this.length) {
                return null;
            }
            return new BABYLON.IntersectionInfo(bu, bv, distance);
        };
        /**
         * Checks if ray intersects a plane
         * @param plane the plane to check
         * @returns the distance away it was hit
         */
        Ray.prototype.intersectsPlane = function (plane) {
            var distance;
            var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
            if (Math.abs(result1) < 9.99999997475243E-07) {
                return null;
            }
            else {
                var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
                distance = (-plane.d - result2) / result1;
                if (distance < 0.0) {
                    if (distance < -9.99999997475243E-07) {
                        return null;
                    }
                    else {
                        return 0;
                    }
                }
                return distance;
            }
        };
        /**
         * Checks if ray intersects a mesh
         * @param mesh the mesh to check
         * @param fastCheck if only the bounding box should checked
         * @returns picking info of the intersecton
         */
        Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
            var tm = BABYLON.Tmp.Matrix[0];
            mesh.getWorldMatrix().invertToRef(tm);
            if (this._tmpRay) {
                Ray.TransformToRef(this, tm, this._tmpRay);
            }
            else {
                this._tmpRay = Ray.Transform(this, tm);
            }
            return mesh.intersects(this._tmpRay, fastCheck);
        };
        /**
         * Checks if ray intersects a mesh
         * @param meshes the meshes to check
         * @param fastCheck if only the bounding box should checked
         * @param results array to store result in
         * @returns Array of picking infos
         */
        Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
            if (results) {
                results.length = 0;
            }
            else {
                results = [];
            }
            for (var i = 0; i < meshes.length; i++) {
                var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
                if (pickInfo.hit) {
                    results.push(pickInfo);
                }
            }
            results.sort(this._comparePickingInfo);
            return results;
        };
        Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
            if (pickingInfoA.distance < pickingInfoB.distance) {
                return -1;
            }
            else if (pickingInfoA.distance > pickingInfoB.distance) {
                return 1;
            }
            else {
                return 0;
            }
        };
        /**
         * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
         * @param sega the first point of the segment to test the intersection against
         * @param segb the second point of the segment to test the intersection against
         * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
         * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
         */
        Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
            var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
            var u = segb.subtract(sega);
            var v = rsegb.subtract(this.origin);
            var w = sega.subtract(this.origin);
            var a = BABYLON.Vector3.Dot(u, u); // always >= 0
            var b = BABYLON.Vector3.Dot(u, v);
            var c = BABYLON.Vector3.Dot(v, v); // always >= 0
            var d = BABYLON.Vector3.Dot(u, w);
            var e = BABYLON.Vector3.Dot(v, w);
            var D = a * c - b * b; // always >= 0
            var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
            var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
            // compute the line parameters of the two closest points
            if (D < Ray.smallnum) { // the lines are almost parallel
                sN = 0.0; // force using point P0 on segment S1
                sD = 1.0; // to prevent possible division by 0.0 later
                tN = e;
                tD = c;
            }
            else { // get the closest points on the infinite lines
                sN = (b * e - c * d);
                tN = (a * e - b * d);
                if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
                    sN = 0.0;
                    tN = e;
                    tD = c;
                }
                else if (sN > sD) { // sc > 1 => the s=1 edge is visible
                    sN = sD;
                    tN = e + b;
                    tD = c;
                }
            }
            if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
                tN = 0.0;
                // recompute sc for this edge
                if (-d < 0.0) {
                    sN = 0.0;
                }
                else if (-d > a) {
                    sN = sD;
                }
                else {
                    sN = -d;
                    sD = a;
                }
            }
            else if (tN > tD) { // tc > 1 => the t=1 edge is visible
                tN = tD;
                // recompute sc for this edge
                if ((-d + b) < 0.0) {
                    sN = 0;
                }
                else if ((-d + b) > a) {
                    sN = sD;
                }
                else {
                    sN = (-d + b);
                    sD = a;
                }
            }
            // finally do the division to get sc and tc
            sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
            tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
            // get the difference of the two closest points
            var qtc = v.multiplyByFloats(tc, tc, tc);
            var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
            var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
            if (isIntersected) {
                return qtc.length();
            }
            return -1;
        };
        /**
         * Update the ray from viewport position
         * @param x position
         * @param y y position
         * @param viewportWidth viewport width
         * @param viewportHeight viewport height
         * @param world world matrix
         * @param view view matrix
         * @param projection projection matrix
         * @returns this ray updated
         */
        Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
            BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
            BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
            BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
            this.direction.normalize();
            return this;
        };
        // Statics
        /**
         * Creates a ray with origin and direction of 0,0,0
         * @returns the new ray
         */
        Ray.Zero = function () {
            return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
        };
        /**
         * Creates a new ray from screen space and viewport
         * @param x position
         * @param y y position
         * @param viewportWidth viewport width
         * @param viewportHeight viewport height
         * @param world world matrix
         * @param view view matrix
         * @param projection projection matrix
         * @returns new ray
         */
        Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
            var result = Ray.Zero();
            return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
        };
        /**
        * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
        * transformed to the given world matrix.
        * @param origin The origin point
        * @param end The end point
        * @param world a matrix to transform the ray to. Default is the identity matrix.
        * @returns the new ray
        */
        Ray.CreateNewFromTo = function (origin, end, world) {
            if (world === void 0) { world = BABYLON.Matrix.Identity(); }
            var direction = end.subtract(origin);
            var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
            direction.normalize();
            return Ray.Transform(new Ray(origin, direction, length), world);
        };
        /**
         * Transforms a ray by a matrix
         * @param ray ray to transform
         * @param matrix matrix to apply
         * @returns the resulting new ray
         */
        Ray.Transform = function (ray, matrix) {
            var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
            Ray.TransformToRef(ray, matrix, result);
            return result;
        };
        /**
         * Transforms a ray by a matrix
         * @param ray ray to transform
         * @param matrix matrix to apply
         * @param result ray to store result in
         */
        Ray.TransformToRef = function (ray, matrix, result) {
            BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
            BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
            result.length = ray.length;
            var dir = result.direction;
            var len = dir.length();
            if (!(len === 0 || len === 1)) {
                var num = 1.0 / len;
                dir.x *= num;
                dir.y *= num;
                dir.z *= num;
                result.length *= len;
            }
        };
        Ray.smallnum = 0.00000001;
        Ray.rayl = 10e8;
        return Ray;
    }());
    BABYLON.Ray = Ray;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.ray.js.map

var BABYLON;
(function (BABYLON) {
    var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
        if (boxMin.x > sphereCenter.x + sphereRadius) {
            return false;
        }
        if (sphereCenter.x - sphereRadius > boxMax.x) {
            return false;
        }
        if (boxMin.y > sphereCenter.y + sphereRadius) {
            return false;
        }
        if (sphereCenter.y - sphereRadius > boxMax.y) {
            return false;
        }
        if (boxMin.z > sphereCenter.z + sphereRadius) {
            return false;
        }
        if (sphereCenter.z - sphereRadius > boxMax.z) {
            return false;
        }
        return true;
    };
    var getLowestRoot = (function () {
        var result = { root: 0, found: false };
        return function (a, b, c, maxR) {
            result.root = 0;
            result.found = false;
            var determinant = b * b - 4.0 * a * c;
            if (determinant < 0) {
                return result;
            }
            var sqrtD = Math.sqrt(determinant);
            var r1 = (-b - sqrtD) / (2.0 * a);
            var r2 = (-b + sqrtD) / (2.0 * a);
            if (r1 > r2) {
                var temp = r2;
                r2 = r1;
                r1 = temp;
            }
            if (r1 > 0 && r1 < maxR) {
                result.root = r1;
                result.found = true;
                return result;
            }
            if (r2 > 0 && r2 < maxR) {
                result.root = r2;
                result.found = true;
                return result;
            }
            return result;
        };
    })();
    /** @hidden */
    var Collider = /** @class */ (function () {
        function Collider() {
            this._collisionPoint = BABYLON.Vector3.Zero();
            this._planeIntersectionPoint = BABYLON.Vector3.Zero();
            this._tempVector = BABYLON.Vector3.Zero();
            this._tempVector2 = BABYLON.Vector3.Zero();
            this._tempVector3 = BABYLON.Vector3.Zero();
            this._tempVector4 = BABYLON.Vector3.Zero();
            this._edge = BABYLON.Vector3.Zero();
            this._baseToVertex = BABYLON.Vector3.Zero();
            this._destinationPoint = BABYLON.Vector3.Zero();
            this._slidePlaneNormal = BABYLON.Vector3.Zero();
            this._displacementVector = BABYLON.Vector3.Zero();
            /** @hidden */
            this._radius = BABYLON.Vector3.One();
            /** @hidden */
            this._retry = 0;
            /** @hidden */
            this._basePointWorld = BABYLON.Vector3.Zero();
            this._velocityWorld = BABYLON.Vector3.Zero();
            this._normalizedVelocity = BABYLON.Vector3.Zero();
            this._collisionMask = -1;
        }
        Object.defineProperty(Collider.prototype, "collisionMask", {
            get: function () {
                return this._collisionMask;
            },
            set: function (mask) {
                this._collisionMask = !isNaN(mask) ? mask : -1;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
            /**
             * Gets the plane normal used to compute the sliding response (in local space)
             */
            get: function () {
                return this._slidePlaneNormal;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /** @hidden */
        Collider.prototype._initialize = function (source, dir, e) {
            this._velocity = dir;
            BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
            this._basePoint = source;
            source.multiplyToRef(this._radius, this._basePointWorld);
            dir.multiplyToRef(this._radius, this._velocityWorld);
            this._velocityWorldLength = this._velocityWorld.length();
            this._epsilon = e;
            this.collisionFound = false;
        };
        /** @hidden */
        Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
            pa.subtractToRef(point, this._tempVector);
            pb.subtractToRef(point, this._tempVector2);
            BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
            var d = BABYLON.Vector3.Dot(this._tempVector4, n);
            if (d < 0) {
                return false;
            }
            pc.subtractToRef(point, this._tempVector3);
            BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
            d = BABYLON.Vector3.Dot(this._tempVector4, n);
            if (d < 0) {
                return false;
            }
            BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
            d = BABYLON.Vector3.Dot(this._tempVector4, n);
            return d >= 0;
        };
        /** @hidden */
        Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
            var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
            var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
            if (distance > this._velocityWorldLength + max + sphereRadius) {
                return false;
            }
            if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
                return false;
            }
            return true;
        };
        /** @hidden */
        Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
            var t0;
            var embeddedInPlane = false;
            //defensive programming, actually not needed.
            if (!trianglePlaneArray) {
                trianglePlaneArray = [];
            }
            if (!trianglePlaneArray[faceIndex]) {
                trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
                trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
            }
            var trianglePlane = trianglePlaneArray[faceIndex];
            if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
                return;
            }
            var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
            var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
            if (normalDotVelocity == 0) {
                if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
                    return;
                }
                embeddedInPlane = true;
                t0 = 0;
            }
            else {
                t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
                var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
                if (t0 > t1) {
                    var temp = t1;
                    t1 = t0;
                    t0 = temp;
                }
                if (t0 > 1.0 || t1 < 0.0) {
                    return;
                }
                if (t0 < 0) {
                    t0 = 0;
                }
                if (t0 > 1.0) {
                    t0 = 1.0;
                }
            }
            this._collisionPoint.copyFromFloats(0, 0, 0);
            var found = false;
            var t = 1.0;
            if (!embeddedInPlane) {
                this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
                this._velocity.scaleToRef(t0, this._tempVector);
                this._planeIntersectionPoint.addInPlace(this._tempVector);
                if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
                    found = true;
                    t = t0;
                    this._collisionPoint.copyFrom(this._planeIntersectionPoint);
                }
            }
            if (!found) {
                var velocitySquaredLength = this._velocity.lengthSquared();
                var a = velocitySquaredLength;
                this._basePoint.subtractToRef(p1, this._tempVector);
                var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
                var c = this._tempVector.lengthSquared() - 1.0;
                var lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    t = lowestRoot.root;
                    found = true;
                    this._collisionPoint.copyFrom(p1);
                }
                this._basePoint.subtractToRef(p2, this._tempVector);
                b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
                c = this._tempVector.lengthSquared() - 1.0;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    t = lowestRoot.root;
                    found = true;
                    this._collisionPoint.copyFrom(p2);
                }
                this._basePoint.subtractToRef(p3, this._tempVector);
                b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
                c = this._tempVector.lengthSquared() - 1.0;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    t = lowestRoot.root;
                    found = true;
                    this._collisionPoint.copyFrom(p3);
                }
                p2.subtractToRef(p1, this._edge);
                p1.subtractToRef(this._basePoint, this._baseToVertex);
                var edgeSquaredLength = this._edge.lengthSquared();
                var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
                var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
                    if (f >= 0.0 && f <= 1.0) {
                        t = lowestRoot.root;
                        found = true;
                        this._edge.scaleInPlace(f);
                        p1.addToRef(this._edge, this._collisionPoint);
                    }
                }
                p3.subtractToRef(p2, this._edge);
                p2.subtractToRef(this._basePoint, this._baseToVertex);
                edgeSquaredLength = this._edge.lengthSquared();
                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
                    if (f >= 0.0 && f <= 1.0) {
                        t = lowestRoot.root;
                        found = true;
                        this._edge.scaleInPlace(f);
                        p2.addToRef(this._edge, this._collisionPoint);
                    }
                }
                p1.subtractToRef(p3, this._edge);
                p3.subtractToRef(this._basePoint, this._baseToVertex);
                edgeSquaredLength = this._edge.lengthSquared();
                edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
                edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
                a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
                b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
                c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
                lowestRoot = getLowestRoot(a, b, c, t);
                if (lowestRoot.found) {
                    f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
                    if (f >= 0.0 && f <= 1.0) {
                        t = lowestRoot.root;
                        found = true;
                        this._edge.scaleInPlace(f);
                        p3.addToRef(this._edge, this._collisionPoint);
                    }
                }
            }
            if (found) {
                var distToCollision = t * this._velocity.length();
                if (!this.collisionFound || distToCollision < this._nearestDistance) {
                    if (!this.intersectionPoint) {
                        this.intersectionPoint = this._collisionPoint.clone();
                    }
                    else {
                        this.intersectionPoint.copyFrom(this._collisionPoint);
                    }
                    this._nearestDistance = distToCollision;
                    this.collisionFound = true;
                }
            }
        };
        /** @hidden */
        Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
            for (var i = indexStart; i < indexEnd; i += 3) {
                var p1 = pts[indices[i] - decal];
                var p2 = pts[indices[i + 1] - decal];
                var p3 = pts[indices[i + 2] - decal];
                this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
            }
        };
        /** @hidden */
        Collider.prototype._getResponse = function (pos, vel) {
            pos.addToRef(vel, this._destinationPoint);
            vel.scaleInPlace((this._nearestDistance / vel.length()));
            this._basePoint.addToRef(vel, pos);
            pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
            this._slidePlaneNormal.normalize();
            this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
            pos.addInPlace(this._displacementVector);
            this.intersectionPoint.addInPlace(this._displacementVector);
            this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
            this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
            this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
        };
        return Collider;
    }());
    BABYLON.Collider = Collider;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.collider.js.map

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

//# sourceMappingURL=babylon.collisionCoordinator.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A particle represents one of the element emitted by a particle system.
     * This is mainly define by its coordinates, direction, velocity and age.
     */
    var Particle = /** @class */ (function () {
        /**
         * Creates a new instance Particle
         * @param particleSystem the particle system the particle belongs to
         */
        function Particle(
        /**
         * The particle system the particle belongs to.
         */
        particleSystem) {
            this.particleSystem = particleSystem;
            /**
             * The world position of the particle in the scene.
             */
            this.position = BABYLON.Vector3.Zero();
            /**
             * The world direction of the particle in the scene.
             */
            this.direction = BABYLON.Vector3.Zero();
            /**
             * The color of the particle.
             */
            this.color = new BABYLON.Color4(0, 0, 0, 0);
            /**
             * The color change of the particle per step.
             */
            this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
            /**
             * Defines how long will the life of the particle be.
             */
            this.lifeTime = 1.0;
            /**
             * The current age of the particle.
             */
            this.age = 0;
            /**
             * The current size of the particle.
             */
            this.size = 0;
            /**
             * The current scale of the particle.
             */
            this.scale = new BABYLON.Vector2(1, 1);
            /**
             * The current angle of the particle.
             */
            this.angle = 0;
            /**
             * Defines how fast is the angle changing.
             */
            this.angularSpeed = 0;
            /**
             * Defines the cell index used by the particle to be rendered from a sprite.
             */
            this.cellIndex = 0;
            /** @hidden */
            this._attachedSubEmitters = null;
            /** @hidden */
            this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
            /** @hidden */
            this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
            /** @hidden */
            this._currentSize1 = 0;
            /** @hidden */
            this._currentSize2 = 0;
            /** @hidden */
            this._currentAngularSpeed1 = 0;
            /** @hidden */
            this._currentAngularSpeed2 = 0;
            /** @hidden */
            this._currentVelocity1 = 0;
            /** @hidden */
            this._currentVelocity2 = 0;
            /** @hidden */
            this._currentLimitVelocity1 = 0;
            /** @hidden */
            this._currentLimitVelocity2 = 0;
            /** @hidden */
            this._currentDrag1 = 0;
            /** @hidden */
            this._currentDrag2 = 0;
            this.id = Particle._Count++;
            if (!this.particleSystem.isAnimationSheetEnabled) {
                return;
            }
            this.updateCellInfoFromSystem();
        }
        Particle.prototype.updateCellInfoFromSystem = function () {
            this.cellIndex = this.particleSystem.startSpriteCellID;
        };
        /**
         * Defines how the sprite cell index is updated for the particle
         */
        Particle.prototype.updateCellIndex = function () {
            var offsetAge = this.age;
            var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
            if (this.particleSystem.spriteRandomStartCell) {
                if (this._randomCellOffset === undefined) {
                    this._randomCellOffset = Math.random() * this.lifeTime;
                }
                if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
                    changeSpeed = 1;
                    offsetAge = this._randomCellOffset;
                }
                else {
                    offsetAge += this._randomCellOffset;
                }
            }
            var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
            var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
            this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
        };
        /** @hidden */
        Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
            if (subEmitter.particleSystem.emitter.position) {
                var emitterMesh = subEmitter.particleSystem.emitter;
                emitterMesh.position.copyFrom(this.position);
                if (subEmitter.inheritDirection) {
                    emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
                    // Look at using Y as forward
                    emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
                }
            }
            else {
                var emitterPosition = subEmitter.particleSystem.emitter;
                emitterPosition.copyFrom(this.position);
            }
            // Set inheritedVelocityOffset to be used when new particles are created
            this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
            subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
        };
        /** @hidden */
        Particle.prototype._inheritParticleInfoToSubEmitters = function () {
            var _this = this;
            if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
                this._attachedSubEmitters.forEach(function (subEmitter) {
                    _this._inheritParticleInfoToSubEmitter(subEmitter);
                });
            }
        };
        /** @hidden */
        Particle.prototype._reset = function () {
            this.age = 0;
            this._currentColorGradient = null;
            this._currentSizeGradient = null;
            this._currentAngularSpeedGradient = null;
            this._currentVelocityGradient = null;
            this._currentLimitVelocityGradient = null;
            this._currentDragGradient = null;
            this.cellIndex = this.particleSystem.startSpriteCellID;
            this._randomCellOffset = undefined;
        };
        /**
         * Copy the properties of particle to another one.
         * @param other the particle to copy the information to.
         */
        Particle.prototype.copyTo = function (other) {
            other.position.copyFrom(this.position);
            if (this._initialDirection) {
                if (other._initialDirection) {
                    other._initialDirection.copyFrom(this._initialDirection);
                }
                else {
                    other._initialDirection = this._initialDirection.clone();
                }
            }
            else {
                other._initialDirection = null;
            }
            other.direction.copyFrom(this.direction);
            other.color.copyFrom(this.color);
            other.colorStep.copyFrom(this.colorStep);
            other.lifeTime = this.lifeTime;
            other.age = this.age;
            other._randomCellOffset = this._randomCellOffset;
            other.size = this.size;
            other.scale.copyFrom(this.scale);
            other.angle = this.angle;
            other.angularSpeed = this.angularSpeed;
            other.particleSystem = this.particleSystem;
            other.cellIndex = this.cellIndex;
            other.id = this.id;
            other._attachedSubEmitters = this._attachedSubEmitters;
            if (this._currentColorGradient) {
                other._currentColorGradient = this._currentColorGradient;
                other._currentColor1.copyFrom(this._currentColor1);
                other._currentColor2.copyFrom(this._currentColor2);
            }
            if (this._currentSizeGradient) {
                other._currentSizeGradient = this._currentSizeGradient;
                other._currentSize1 = this._currentSize1;
                other._currentSize2 = this._currentSize2;
            }
            if (this._currentAngularSpeedGradient) {
                other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
                other._currentAngularSpeed1 = this._currentAngularSpeed1;
                other._currentAngularSpeed2 = this._currentAngularSpeed2;
            }
            if (this._currentVelocityGradient) {
                other._currentVelocityGradient = this._currentVelocityGradient;
                other._currentVelocity1 = this._currentVelocity1;
                other._currentVelocity2 = this._currentVelocity2;
            }
            if (this._currentLimitVelocityGradient) {
                other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
                other._currentLimitVelocity1 = this._currentLimitVelocity1;
                other._currentLimitVelocity2 = this._currentLimitVelocity2;
            }
            if (this._currentDragGradient) {
                other._currentDragGradient = this._currentDragGradient;
                other._currentDrag1 = this._currentDrag1;
                other._currentDrag2 = this._currentDrag2;
            }
            if (this.particleSystem.isAnimationSheetEnabled) {
                other._initialStartSpriteCellID = this._initialStartSpriteCellID;
                other._initialEndSpriteCellID = this._initialEndSpriteCellID;
            }
            if (this.particleSystem.useRampGradients) {
                other.remapData.copyFrom(this.remapData);
            }
            if (this._randomNoiseCoordinates1) {
                if (other._randomNoiseCoordinates1) {
                    other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
                    other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
                }
                else {
                    other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
                    other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
                }
            }
        };
        Particle._Count = 0;
        return Particle;
    }());
    BABYLON.Particle = Particle;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.particle.js.map

var BABYLON;
(function (BABYLON) {
    /**
   * This represents the base class for particle system in Babylon.
   * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
   * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
   * @example https://doc.babylonjs.com/babylon101/particles
   */
    var BaseParticleSystem = /** @class */ (function () {
        /**
         * Instantiates a particle system.
         * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
         * @param name The name of the particle system
         */
        function BaseParticleSystem(name) {
            /**
             * List of animations used by the particle system.
             */
            this.animations = [];
            /**
             * The rendering group used by the Particle system to chose when to render.
             */
            this.renderingGroupId = 0;
            /**
             * The emitter represents the Mesh or position we are attaching the particle system to.
             */
            this.emitter = null;
            /**
             * The maximum number of particles to emit per frame
             */
            this.emitRate = 10;
            /**
             * If you want to launch only a few particles at once, that can be done, as well.
             */
            this.manualEmitCount = -1;
            /**
             * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
             */
            this.updateSpeed = 0.01;
            /**
             * The amount of time the particle system is running (depends of the overall update speed).
             */
            this.targetStopDuration = 0;
            /**
             * Specifies whether the particle system will be disposed once it reaches the end of the animation.
             */
            this.disposeOnStop = false;
            /**
             * Minimum power of emitting particles.
             */
            this.minEmitPower = 1;
            /**
             * Maximum power of emitting particles.
             */
            this.maxEmitPower = 1;
            /**
             * Minimum life time of emitting particles.
             */
            this.minLifeTime = 1;
            /**
             * Maximum life time of emitting particles.
             */
            this.maxLifeTime = 1;
            /**
             * Minimum Size of emitting particles.
             */
            this.minSize = 1;
            /**
             * Maximum Size of emitting particles.
             */
            this.maxSize = 1;
            /**
             * Minimum scale of emitting particles on X axis.
             */
            this.minScaleX = 1;
            /**
             * Maximum scale of emitting particles on X axis.
             */
            this.maxScaleX = 1;
            /**
             * Minimum scale of emitting particles on Y axis.
             */
            this.minScaleY = 1;
            /**
             * Maximum scale of emitting particles on Y axis.
             */
            this.maxScaleY = 1;
            /**
             * Gets or sets the minimal initial rotation in radians.
             */
            this.minInitialRotation = 0;
            /**
             * Gets or sets the maximal initial rotation in radians.
             */
            this.maxInitialRotation = 0;
            /**
             * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
             */
            this.minAngularSpeed = 0;
            /**
             * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
             */
            this.maxAngularSpeed = 0;
            /**
             * The layer mask we are rendering the particles through.
             */
            this.layerMask = 0x0FFFFFFF;
            /**
             * This can help using your own shader to render the particle system.
             * The according effect will be created
             */
            this.customShader = null;
            /**
             * By default particle system starts as soon as they are created. This prevents the
             * automatic start to happen and let you decide when to start emitting particles.
             */
            this.preventAutoStart = false;
            /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
            this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
            /**
             * Callback triggered when the particle animation is ending.
             */
            this.onAnimationEnd = null;
            /**
             * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
             */
            this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
            /**
             * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
             * to override the particles.
             */
            this.forceDepthWrite = false;
            /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
            this.preWarmCycles = 0;
            /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
            this.preWarmStepOffset = 1;
            /**
             * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
             */
            this.spriteCellChangeSpeed = 1;
            /**
             * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
             */
            this.startSpriteCellID = 0;
            /**
             * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
             */
            this.endSpriteCellID = 0;
            /**
             * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
             */
            this.spriteCellWidth = 0;
            /**
             * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
             */
            this.spriteCellHeight = 0;
            /**
             * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
             */
            this.spriteRandomStartCell = false;
            /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
            this.translationPivot = new BABYLON.Vector2(0, 0);
            /**
             * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
             */
            this.beginAnimationOnStart = false;
            /**
             * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
             */
            this.beginAnimationFrom = 0;
            /**
             * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
             */
            this.beginAnimationTo = 60;
            /**
             * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
             */
            this.beginAnimationLoop = false;
            /**
             * You can use gravity if you want to give an orientation to your particles.
             */
            this.gravity = BABYLON.Vector3.Zero();
            this._colorGradients = null;
            this._sizeGradients = null;
            this._lifeTimeGradients = null;
            this._angularSpeedGradients = null;
            this._velocityGradients = null;
            this._limitVelocityGradients = null;
            this._dragGradients = null;
            this._emitRateGradients = null;
            this._startSizeGradients = null;
            this._rampGradients = null;
            this._colorRemapGradients = null;
            this._alphaRemapGradients = null;
            /**
             * Defines the delay in milliseconds before starting the system (0 by default)
             */
            this.startDelay = 0;
            /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
            this.limitVelocityDamping = 0.4;
            /**
             * Random color of each particle after it has been emitted, between color1 and color2 vectors
             */
            this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            /**
             * Random color of each particle after it has been emitted, between color1 and color2 vectors
             */
            this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            /**
             * Color the particle will have at the end of its lifetime
             */
            this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
            /**
             * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
             */
            this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            /** @hidden */
            this._isSubEmitter = false;
            /**
             * Gets or sets the billboard mode to use when isBillboardBased = true.
             * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
             */
            this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
            this._isBillboardBased = true;
            /**
             * Local cache of defines for image processing.
             */
            this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
            this.id = name;
            this.name = name;
        }
        Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
            /**
             * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
             */
            get: function () {
                return this._isAnimationSheetEnabled;
            },
            set: function (value) {
                if (this._isAnimationSheetEnabled == value) {
                    return;
                }
                this._isAnimationSheetEnabled = value;
                this._reset();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get hosting scene
         * @returns the scene
         */
        BaseParticleSystem.prototype.getScene = function () {
            return this._scene;
        };
        BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
            return (this._startSizeGradients && this._startSizeGradients.length > 0)
                || (this._emitRateGradients && this._emitRateGradients.length > 0)
                || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
        };
        /**
         * Gets the current list of drag gradients.
         * You must use addDragGradient and removeDragGradient to udpate this list
         * @returns the list of drag gradients
         */
        BaseParticleSystem.prototype.getDragGradients = function () {
            return this._dragGradients;
        };
        /**
         * Gets the current list of limit velocity gradients.
         * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
         * @returns the list of limit velocity gradients
         */
        BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
            return this._limitVelocityGradients;
        };
        /**
         * Gets the current list of color gradients.
         * You must use addColorGradient and removeColorGradient to udpate this list
         * @returns the list of color gradients
         */
        BaseParticleSystem.prototype.getColorGradients = function () {
            return this._colorGradients;
        };
        /**
         * Gets the current list of size gradients.
         * You must use addSizeGradient and removeSizeGradient to udpate this list
         * @returns the list of size gradients
         */
        BaseParticleSystem.prototype.getSizeGradients = function () {
            return this._sizeGradients;
        };
        /**
         * Gets the current list of color remap gradients.
         * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
         * @returns the list of color remap gradients
         */
        BaseParticleSystem.prototype.getColorRemapGradients = function () {
            return this._colorRemapGradients;
        };
        /**
         * Gets the current list of alpha remap gradients.
         * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
         * @returns the list of alpha remap gradients
         */
        BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
            return this._alphaRemapGradients;
        };
        /**
         * Gets the current list of life time gradients.
         * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
         * @returns the list of life time gradients
         */
        BaseParticleSystem.prototype.getLifeTimeGradients = function () {
            return this._lifeTimeGradients;
        };
        /**
         * Gets the current list of angular speed gradients.
         * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
         * @returns the list of angular speed gradients
         */
        BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
            return this._angularSpeedGradients;
        };
        /**
         * Gets the current list of velocity gradients.
         * You must use addVelocityGradient and removeVelocityGradient to udpate this list
         * @returns the list of velocity gradients
         */
        BaseParticleSystem.prototype.getVelocityGradients = function () {
            return this._velocityGradients;
        };
        /**
         * Gets the current list of start size gradients.
         * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
         * @returns the list of start size gradients
         */
        BaseParticleSystem.prototype.getStartSizeGradients = function () {
            return this._startSizeGradients;
        };
        /**
         * Gets the current list of emit rate gradients.
         * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
         * @returns the list of emit rate gradients
         */
        BaseParticleSystem.prototype.getEmitRateGradients = function () {
            return this._emitRateGradients;
        };
        Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
            /**
             * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
             * This only works when particleEmitterTyps is a BoxParticleEmitter
             */
            get: function () {
                if (this.particleEmitterType.direction1) {
                    return this.particleEmitterType.direction1;
                }
                return BABYLON.Vector3.Zero();
            },
            set: function (value) {
                if (this.particleEmitterType.direction1) {
                    this.particleEmitterType.direction1 = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
            /**
             * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
             * This only works when particleEmitterTyps is a BoxParticleEmitter
             */
            get: function () {
                if (this.particleEmitterType.direction2) {
                    return this.particleEmitterType.direction2;
                }
                return BABYLON.Vector3.Zero();
            },
            set: function (value) {
                if (this.particleEmitterType.direction2) {
                    this.particleEmitterType.direction2 = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
            /**
             * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
             * This only works when particleEmitterTyps is a BoxParticleEmitter
             */
            get: function () {
                if (this.particleEmitterType.minEmitBox) {
                    return this.particleEmitterType.minEmitBox;
                }
                return BABYLON.Vector3.Zero();
            },
            set: function (value) {
                if (this.particleEmitterType.minEmitBox) {
                    this.particleEmitterType.minEmitBox = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
            /**
             * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
             * This only works when particleEmitterTyps is a BoxParticleEmitter
             */
            get: function () {
                if (this.particleEmitterType.maxEmitBox) {
                    return this.particleEmitterType.maxEmitBox;
                }
                return BABYLON.Vector3.Zero();
            },
            set: function (value) {
                if (this.particleEmitterType.maxEmitBox) {
                    this.particleEmitterType.maxEmitBox = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
            /**
             * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
             */
            get: function () {
                return this._isBillboardBased;
            },
            set: function (value) {
                if (this._isBillboardBased === value) {
                    return;
                }
                this._isBillboardBased = value;
                this._reset();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
            /**
             * Gets the image processing configuration used either in this material.
             */
            get: function () {
                return this._imageProcessingConfiguration;
            },
            /**
             * Sets the Default image processing configuration used either in the this material.
             *
             * If sets to null, the scene one is in use.
             */
            set: function (value) {
                this._attachImageProcessingConfiguration(value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attaches a new image processing configuration to the Standard Material.
         * @param configuration
         */
        BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
            if (configuration === this._imageProcessingConfiguration) {
                return;
            }
            // Pick the scene configuration if needed.
            if (!configuration) {
                this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
            }
            else {
                this._imageProcessingConfiguration = configuration;
            }
        };
        /** @hidden */
        BaseParticleSystem.prototype._reset = function () {
        };
        /** @hidden */
        BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
            if (!gradients) {
                return this;
            }
            var index = 0;
            for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
                var valueGradient = gradients_1[_i];
                if (valueGradient.gradient === gradient) {
                    gradients.splice(index, 1);
                    break;
                }
                index++;
            }
            if (texture) {
                texture.dispose();
            }
            return this;
        };
        /**
         * Creates a Point Emitter for the particle system (emits directly from the emitter position)
         * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
         * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
            var particleEmitter = new BABYLON.PointParticleEmitter();
            particleEmitter.direction1 = direction1;
            particleEmitter.direction2 = direction2;
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
         * @param radius The radius of the hemisphere to emit from
         * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
            if (radius === void 0) { radius = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
         * @param radius The radius of the sphere to emit from
         * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
            if (radius === void 0) { radius = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
         * @param radius The radius of the sphere to emit from
         * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
         * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
            if (radius === void 0) { radius = 1; }
            if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
            if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
            var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
         * @param radius The radius of the emission cylinder
         * @param height The height of the emission cylinder
         * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
         * @param directionRandomizer How much to randomize the particle direction [0-1]
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
            if (radius === void 0) { radius = 1; }
            if (height === void 0) { height = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            if (directionRandomizer === void 0) { directionRandomizer = 0; }
            var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
         * @param radius The radius of the cylinder to emit from
         * @param height The height of the emission cylinder
         * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
         * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
         * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
            if (radius === void 0) { radius = 1; }
            if (height === void 0) { height = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
            if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
            var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
         * @param radius The radius of the cone to emit from
         * @param angle The base angle of the cone
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
            if (radius === void 0) { radius = 1; }
            if (angle === void 0) { angle = Math.PI / 4; }
            var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
            this.particleEmitterType = particleEmitter;
            return particleEmitter;
        };
        /**
         * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
         * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
         * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
         * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
         * @param maxEmitBox  Particles are emitted from the box between minEmitBox and maxEmitBox
         * @returns the emitter
         */
        BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
            var particleEmitter = new BABYLON.BoxParticleEmitter();
            this.particleEmitterType = particleEmitter;
            this.direction1 = direction1;
            this.direction2 = direction2;
            this.minEmitBox = minEmitBox;
            this.maxEmitBox = maxEmitBox;
            return particleEmitter;
        };
        /**
         * Source color is added to the destination color without alpha affecting the result
         */
        BaseParticleSystem.BLENDMODE_ONEONE = 0;
        /**
         * Blend current color and particle color using particle’s alpha
         */
        BaseParticleSystem.BLENDMODE_STANDARD = 1;
        /**
         * Add current color and particle color multiplied by particle’s alpha
         */
        BaseParticleSystem.BLENDMODE_ADD = 2;
        /**
         * Multiply current color with particle color
         */
        BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
        /**
         * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
         */
        BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
        return BaseParticleSystem;
    }());
    BABYLON.BaseParticleSystem = BaseParticleSystem;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.baseParticleSystem.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This represents a particle system in Babylon.
     * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
     * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
     * @example https://doc.babylonjs.com/babylon101/particles
     */
    var ParticleSystem = /** @class */ (function (_super) {
        __extends(ParticleSystem, _super);
        /**
         * Instantiates a particle system.
         * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
         * @param name The name of the particle system
         * @param capacity The max number of particles alive at the same time
         * @param scene The scene the particle system belongs to
         * @param customEffect a custom effect used to change the way particles are rendered by default
         * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
         * @param epsilon Offset used to render the particles
         */
        function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
            if (customEffect === void 0) { customEffect = null; }
            if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
            if (epsilon === void 0) { epsilon = 0.01; }
            var _this = _super.call(this, name) || this;
            /**
             * @hidden
             */
            _this._inheritedVelocityOffset = new BABYLON.Vector3();
            /**
            * An event triggered when the system is disposed
            */
            _this.onDisposeObservable = new BABYLON.Observable();
            _this._particles = new Array();
            _this._stockParticles = new Array();
            _this._newPartsExcess = 0;
            _this._vertexBuffers = {};
            _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
            _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
            _this._scaledDirection = BABYLON.Vector3.Zero();
            _this._scaledGravity = BABYLON.Vector3.Zero();
            _this._currentRenderId = -1;
            _this._useInstancing = false;
            _this._started = false;
            _this._stopped = false;
            _this._actualFrame = 0;
            /** @hidden */
            _this._currentEmitRate1 = 0;
            /** @hidden */
            _this._currentEmitRate2 = 0;
            /** @hidden */
            _this._currentStartSize1 = 0;
            /** @hidden */
            _this._currentStartSize2 = 0;
            _this._rawTextureWidth = 256;
            _this._useRampGradients = false;
            /**
             * @hidden
             * If the particle systems emitter should be disposed when the particle system is disposed
             */
            _this._disposeEmitterOnDispose = false;
            // start of sub system methods
            /**
             * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
             * Its lifetime will start back at 0.
             */
            _this.recycleParticle = function (particle) {
                // move particle from activeParticle list to stock particles
                var lastParticle = _this._particles.pop();
                if (lastParticle !== particle) {
                    lastParticle.copyTo(particle);
                }
                _this._stockParticles.push(lastParticle);
            };
            _this._createParticle = function () {
                var particle;
                if (_this._stockParticles.length !== 0) {
                    particle = _this._stockParticles.pop();
                    particle._reset();
                }
                else {
                    particle = new BABYLON.Particle(_this);
                }
                // Attach emitters
                if (_this._subEmitters && _this._subEmitters.length > 0) {
                    var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
                    particle._attachedSubEmitters = [];
                    subEmitters.forEach(function (subEmitter) {
                        if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
                            var newEmitter = subEmitter.clone();
                            particle._attachedSubEmitters.push(newEmitter);
                            newEmitter.particleSystem.start();
                        }
                    });
                }
                return particle;
            };
            _this._emitFromParticle = function (particle) {
                if (!_this._subEmitters || _this._subEmitters.length === 0) {
                    return;
                }
                var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
                _this._subEmitters[templateIndex].forEach(function (subEmitter) {
                    if (subEmitter.type === BABYLON.SubEmitterType.END) {
                        var subSystem = subEmitter.clone();
                        particle._inheritParticleInfoToSubEmitter(subSystem);
                        subSystem.particleSystem._rootParticleSystem = _this;
                        _this.activeSubSystems.push(subSystem.particleSystem);
                        subSystem.particleSystem.start();
                    }
                });
            };
            _this._capacity = capacity;
            _this._epsilon = epsilon;
            _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
            _this._scene = scene || BABYLON.Engine.LastCreatedScene;
            // Setup the default processing configuration to the scene.
            _this._attachImageProcessingConfiguration(null);
            _this._customEffect = customEffect;
            _this._scene.particleSystems.push(_this);
            _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
            _this._createIndexBuffer();
            _this._createVertexBuffers();
            // Default emitter type
            _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
            // Update
            _this.updateFunction = function (particles) {
                var noiseTextureSize = null;
                var noiseTextureData = null;
                if (_this.noiseTexture) { // We need to get texture data back to CPU
                    noiseTextureSize = _this.noiseTexture.getSize();
                    noiseTextureData = (_this.noiseTexture.getContent());
                }
                var _loop_1 = function () {
                    particle = particles[index];
                    var scaledUpdateSpeed = _this._scaledUpdateSpeed;
                    var previousAge = particle.age;
                    particle.age += scaledUpdateSpeed;
                    // Evaluate step to death
                    if (particle.age > particle.lifeTime) {
                        var diff = particle.age - previousAge;
                        var oldDiff = particle.lifeTime - previousAge;
                        scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
                        particle.age = particle.lifeTime;
                    }
                    var ratio = particle.age / particle.lifeTime;
                    // Color
                    if (_this._colorGradients && _this._colorGradients.length > 0) {
                        BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
                            if (currentGradient !== particle._currentColorGradient) {
                                particle._currentColor1.copyFrom(particle._currentColor2);
                                nextGradient.getColorToRef(particle._currentColor2);
                                particle._currentColorGradient = currentGradient;
                            }
                            BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
                        });
                    }
                    else {
                        particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
                        particle.color.addInPlace(_this._scaledColorStep);
                        if (particle.color.a < 0) {
                            particle.color.a = 0;
                        }
                    }
                    // Angular speed
                    if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
                        BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
                            if (currentGradient !== particle._currentAngularSpeedGradient) {
                                particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
                                particle._currentAngularSpeed2 = nextGradient.getFactor();
                                particle._currentAngularSpeedGradient = currentGradient;
                            }
                            particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
                        });
                    }
                    particle.angle += particle.angularSpeed * scaledUpdateSpeed;
                    // Direction
                    var directionScale = scaledUpdateSpeed;
                    /// Velocity
                    if (_this._velocityGradients && _this._velocityGradients.length > 0) {
                        BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
                            if (currentGradient !== particle._currentVelocityGradient) {
                                particle._currentVelocity1 = particle._currentVelocity2;
                                particle._currentVelocity2 = nextGradient.getFactor();
                                particle._currentVelocityGradient = currentGradient;
                            }
                            directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
                        });
                    }
                    particle.direction.scaleToRef(directionScale, _this._scaledDirection);
                    /// Limit velocity
                    if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
                        BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
                            if (currentGradient !== particle._currentLimitVelocityGradient) {
                                particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
                                particle._currentLimitVelocity2 = nextGradient.getFactor();
                                particle._currentLimitVelocityGradient = currentGradient;
                            }
                            var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
                            var currentVelocity = particle.direction.length();
                            if (currentVelocity > limitVelocity) {
                                particle.direction.scaleInPlace(_this.limitVelocityDamping);
                            }
                        });
                    }
                    /// Drag
                    if (_this._dragGradients && _this._dragGradients.length > 0) {
                        BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
                            if (currentGradient !== particle._currentDragGradient) {
                                particle._currentDrag1 = particle._currentDrag2;
                                particle._currentDrag2 = nextGradient.getFactor();
                                particle._currentDragGradient = currentGradient;
                            }
                            var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
                            _this._scaledDirection.scaleInPlace(1.0 - drag);
                        });
                    }
                    particle.position.addInPlace(_this._scaledDirection);
                    // Noise
                    if (noiseTextureData && noiseTextureSize) {
                        var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
                        var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
                        var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
                        var force = BABYLON.Tmp.Vector3[0];
                        var scaledForce = BABYLON.Tmp.Vector3[1];
                        force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
                        force.scaleToRef(scaledUpdateSpeed, scaledForce);
                        particle.direction.addInPlace(scaledForce);
                    }
                    // Gravity
                    _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
                    particle.direction.addInPlace(_this._scaledGravity);
                    // Size
                    if (_this._sizeGradients && _this._sizeGradients.length > 0) {
                        BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
                            if (currentGradient !== particle._currentSizeGradient) {
                                particle._currentSize1 = particle._currentSize2;
                                particle._currentSize2 = nextGradient.getFactor();
                                particle._currentSizeGradient = currentGradient;
                            }
                            particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
                        });
                    }
                    // Remap data
                    if (_this._useRampGradients) {
                        if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
                            BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
                                var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
                                var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
                                particle.remapData.x = min;
                                particle.remapData.y = max - min;
                            });
                        }
                        if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
                            BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
                                var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
                                var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
                                particle.remapData.z = min;
                                particle.remapData.w = max - min;
                            });
                        }
                    }
                    if (_this._isAnimationSheetEnabled) {
                        particle.updateCellIndex();
                    }
                    // Update the position of the attached sub-emitters to match their attached particle
                    particle._inheritParticleInfoToSubEmitters();
                    if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
                        _this._emitFromParticle(particle);
                        if (particle._attachedSubEmitters) {
                            particle._attachedSubEmitters.forEach(function (subEmitter) {
                                subEmitter.particleSystem.disposeOnStop = true;
                                subEmitter.particleSystem.stop();
                            });
                            particle._attachedSubEmitters = null;
                        }
                        _this.recycleParticle(particle);
                        index--;
                        return "continue";
                    }
                };
                var particle;
                for (var index = 0; index < particles.length; index++) {
                    _loop_1();
                }
            };
            return _this;
        }
        Object.defineProperty(ParticleSystem.prototype, "onDispose", {
            /**
             * Sets a callback that will be triggered when the system is disposed
             */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
            /** Gets or sets a boolean indicating that ramp gradients must be used
             * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
             */
            get: function () {
                return this._useRampGradients;
            },
            set: function (value) {
                if (this._useRampGradients === value) {
                    return;
                }
                this._useRampGradients = value;
                this._resetEffect();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ParticleSystem.prototype, "particles", {
            //end of Sub-emitter
            /**
             * Gets the current list of active particles
             */
            get: function () {
                return this._particles;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "ParticleSystem"
         * @returns a string containing the class name
         */
        ParticleSystem.prototype.getClassName = function () {
            return "ParticleSystem";
        };
        ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
            var newGradient = new BABYLON.FactorGradient();
            newGradient.gradient = gradient;
            newGradient.factor1 = factor;
            newGradient.factor2 = factor2;
            factorGradients.push(newGradient);
            factorGradients.sort(function (a, b) {
                if (a.gradient < b.gradient) {
                    return -1;
                }
                else if (a.gradient > b.gradient) {
                    return 1;
                }
                return 0;
            });
        };
        ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
            if (!factorGradients) {
                return;
            }
            var index = 0;
            for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
                var factorGradient = factorGradients_1[_i];
                if (factorGradient.gradient === gradient) {
                    factorGradients.splice(index, 1);
                    break;
                }
                index++;
            }
        };
        /**
         * Adds a new life time gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the life time factor to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
            if (!this._lifeTimeGradients) {
                this._lifeTimeGradients = [];
            }
            this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific life time gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
            this._removeFactorGradient(this._lifeTimeGradients, gradient);
            return this;
        };
        /**
         * Adds a new size gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the size factor to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
            if (!this._sizeGradients) {
                this._sizeGradients = [];
            }
            this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific size gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeSizeGradient = function (gradient) {
            this._removeFactorGradient(this._sizeGradients, gradient);
            return this;
        };
        /**
         * Adds a new color remap gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param min defines the color remap minimal range
         * @param max defines the color remap maximal range
         * @returns the current particle system
         */
        ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
            if (!this._colorRemapGradients) {
                this._colorRemapGradients = [];
            }
            this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
            return this;
        };
        /**
         * Remove a specific color remap gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
            this._removeFactorGradient(this._colorRemapGradients, gradient);
            return this;
        };
        /**
         * Adds a new alpha remap gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param min defines the alpha remap minimal range
         * @param max defines the alpha remap maximal range
         * @returns the current particle system
         */
        ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
            if (!this._alphaRemapGradients) {
                this._alphaRemapGradients = [];
            }
            this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
            return this;
        };
        /**
         * Remove a specific alpha remap gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
            this._removeFactorGradient(this._alphaRemapGradients, gradient);
            return this;
        };
        /**
         * Adds a new angular speed gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the angular speed  to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
            if (!this._angularSpeedGradients) {
                this._angularSpeedGradients = [];
            }
            this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific angular speed gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
            this._removeFactorGradient(this._angularSpeedGradients, gradient);
            return this;
        };
        /**
         * Adds a new velocity gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the velocity to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
            if (!this._velocityGradients) {
                this._velocityGradients = [];
            }
            this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific velocity gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
            this._removeFactorGradient(this._velocityGradients, gradient);
            return this;
        };
        /**
         * Adds a new limit velocity gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the limit velocity value to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
            if (!this._limitVelocityGradients) {
                this._limitVelocityGradients = [];
            }
            this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific limit velocity gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
            this._removeFactorGradient(this._limitVelocityGradients, gradient);
            return this;
        };
        /**
         * Adds a new drag gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the drag value to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
            if (!this._dragGradients) {
                this._dragGradients = [];
            }
            this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific drag gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeDragGradient = function (gradient) {
            this._removeFactorGradient(this._dragGradients, gradient);
            return this;
        };
        /**
         * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the emit rate value to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
            if (!this._emitRateGradients) {
                this._emitRateGradients = [];
            }
            this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific emit rate gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
            this._removeFactorGradient(this._emitRateGradients, gradient);
            return this;
        };
        /**
         * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the start size value to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
            if (!this._startSizeGradients) {
                this._startSizeGradients = [];
            }
            this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
            return this;
        };
        /**
         * Remove a specific start size gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
            this._removeFactorGradient(this._emitRateGradients, gradient);
            return this;
        };
        ParticleSystem.prototype._createRampGradientTexture = function () {
            if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
                return;
            }
            var data = new Uint8Array(this._rawTextureWidth * 4);
            var tmpColor = BABYLON.Tmp.Color3[0];
            for (var x = 0; x < this._rawTextureWidth; x++) {
                var ratio = x / this._rawTextureWidth;
                BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
                    BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
                    data[x * 4] = tmpColor.r * 255;
                    data[x * 4 + 1] = tmpColor.g * 255;
                    data[x * 4 + 2] = tmpColor.b * 255;
                    data[x * 4 + 3] = 255;
                });
            }
            this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
        };
        /**
         * Gets the current list of ramp gradients.
         * You must use addRampGradient and removeRampGradient to udpate this list
         * @returns the list of ramp gradients
         */
        ParticleSystem.prototype.getRampGradients = function () {
            return this._rampGradients;
        };
        /**
         * Adds a new ramp gradient used to remap particle colors
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param color defines the color to affect to the specified gradient
         * @returns the current particle system
         */
        ParticleSystem.prototype.addRampGradient = function (gradient, color) {
            if (!this._rampGradients) {
                this._rampGradients = [];
            }
            var rampGradient = new BABYLON.Color3Gradient();
            rampGradient.gradient = gradient;
            rampGradient.color = color;
            this._rampGradients.push(rampGradient);
            this._rampGradients.sort(function (a, b) {
                if (a.gradient < b.gradient) {
                    return -1;
                }
                else if (a.gradient > b.gradient) {
                    return 1;
                }
                return 0;
            });
            if (this._rampGradientsTexture) {
                this._rampGradientsTexture.dispose();
                this._rampGradientsTexture = null;
            }
            this._createRampGradientTexture();
            return this;
        };
        /**
         * Remove a specific ramp gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        ParticleSystem.prototype.removeRampGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
            this._rampGradientsTexture = null;
            if (this._rampGradients && this._rampGradients.length > 0) {
                this._createRampGradientTexture();
            }
            return this;
        };
        /**
         * Adds a new color gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param color1 defines the color to affect to the specified gradient
         * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
         * @returns this particle system
         */
        ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
            if (!this._colorGradients) {
                this._colorGradients = [];
            }
            var colorGradient = new BABYLON.ColorGradient();
            colorGradient.gradient = gradient;
            colorGradient.color1 = color1;
            colorGradient.color2 = color2;
            this._colorGradients.push(colorGradient);
            this._colorGradients.sort(function (a, b) {
                if (a.gradient < b.gradient) {
                    return -1;
                }
                else if (a.gradient > b.gradient) {
                    return 1;
                }
                return 0;
            });
            return this;
        };
        /**
         * Remove a specific color gradient
         * @param gradient defines the gradient to remove
         * @returns this particle system
         */
        ParticleSystem.prototype.removeColorGradient = function (gradient) {
            if (!this._colorGradients) {
                return this;
            }
            var index = 0;
            for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
                var colorGradient = _a[_i];
                if (colorGradient.gradient === gradient) {
                    this._colorGradients.splice(index, 1);
                    break;
                }
                index++;
            }
            return this;
        };
        ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
            u = Math.abs(u) * 0.5 + 0.5;
            v = Math.abs(v) * 0.5 + 0.5;
            var wrappedU = ((u * width) % width) | 0;
            var wrappedV = ((v * height) % height) | 0;
            var position = (wrappedU + wrappedV * width) * 4;
            return pixels[position] / 255;
        };
        ParticleSystem.prototype._reset = function () {
            this._resetEffect();
        };
        ParticleSystem.prototype._resetEffect = function () {
            if (this._vertexBuffer) {
                this._vertexBuffer.dispose();
                this._vertexBuffer = null;
            }
            if (this._spriteBuffer) {
                this._spriteBuffer.dispose();
                this._spriteBuffer = null;
            }
            this._createVertexBuffers();
        };
        ParticleSystem.prototype._createVertexBuffers = function () {
            this._vertexBufferSize = this._useInstancing ? 10 : 12;
            if (this._isAnimationSheetEnabled) {
                this._vertexBufferSize += 1;
            }
            if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
                this._vertexBufferSize += 3;
            }
            if (this._useRampGradients) {
                this._vertexBufferSize += 4;
            }
            var engine = this._scene.getEngine();
            this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
            this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
            var dataOffset = 0;
            var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
            dataOffset += 3;
            var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
            dataOffset += 4;
            var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers["angle"] = options;
            dataOffset += 1;
            var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
            this._vertexBuffers["size"] = size;
            dataOffset += 2;
            if (this._isAnimationSheetEnabled) {
                var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
                this._vertexBuffers["cellIndex"] = cellIndexBuffer;
                dataOffset += 1;
            }
            if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
                var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
                this._vertexBuffers["direction"] = directionBuffer;
                dataOffset += 3;
            }
            if (this._useRampGradients) {
                var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
                this._vertexBuffers["remapData"] = rampDataBuffer;
                dataOffset += 4;
            }
            var offsets;
            if (this._useInstancing) {
                var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
                this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
                offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
            }
            else {
                offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
                dataOffset += 2;
            }
            this._vertexBuffers["offset"] = offsets;
        };
        ParticleSystem.prototype._createIndexBuffer = function () {
            if (this._useInstancing) {
                return;
            }
            var indices = [];
            var index = 0;
            for (var count = 0; count < this._capacity; count++) {
                indices.push(index);
                indices.push(index + 1);
                indices.push(index + 2);
                indices.push(index);
                indices.push(index + 2);
                indices.push(index + 3);
                index += 4;
            }
            this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
        };
        /**
         * Gets the maximum number of particles active at the same time.
         * @returns The max number of active particles.
         */
        ParticleSystem.prototype.getCapacity = function () {
            return this._capacity;
        };
        /**
         * Gets whether there are still active particles in the system.
         * @returns True if it is alive, otherwise false.
         */
        ParticleSystem.prototype.isAlive = function () {
            return this._alive;
        };
        /**
         * Gets if the system has been started. (Note: this will still be true after stop is called)
         * @returns True if it has been started, otherwise false.
         */
        ParticleSystem.prototype.isStarted = function () {
            return this._started;
        };
        ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
            var _this = this;
            this._subEmitters = new Array();
            if (this.subEmitters) {
                this.subEmitters.forEach(function (subEmitter) {
                    if (subEmitter instanceof ParticleSystem) {
                        _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
                    }
                    else if (subEmitter instanceof BABYLON.SubEmitter) {
                        _this._subEmitters.push([subEmitter]);
                    }
                    else if (subEmitter instanceof Array) {
                        _this._subEmitters.push(subEmitter);
                    }
                });
            }
        };
        /**
         * Starts the particle system and begins to emit
         * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
         */
        ParticleSystem.prototype.start = function (delay) {
            var _this = this;
            if (delay === void 0) { delay = this.startDelay; }
            if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
                throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
            }
            if (delay) {
                setTimeout(function () {
                    _this.start(0);
                }, delay);
                return;
            }
            // Convert the subEmitters field to the constant type field _subEmitters
            this._prepareSubEmitterInternalArray();
            this._started = true;
            this._stopped = false;
            this._actualFrame = 0;
            if (this._subEmitters && this._subEmitters.length != 0) {
                this.activeSubSystems = new Array();
            }
            // Reset emit gradient so it acts the same on every start
            if (this._emitRateGradients) {
                if (this._emitRateGradients.length > 0) {
                    this._currentEmitRateGradient = this._emitRateGradients[0];
                    this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
                    this._currentEmitRate2 = this._currentEmitRate1;
                }
                if (this._emitRateGradients.length > 1) {
                    this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
                }
            }
            // Reset start size gradient so it acts the same on every start
            if (this._startSizeGradients) {
                if (this._startSizeGradients.length > 0) {
                    this._currentStartSizeGradient = this._startSizeGradients[0];
                    this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
                    this._currentStartSize2 = this._currentStartSize1;
                }
                if (this._startSizeGradients.length > 1) {
                    this._currentStartSize2 = this._startSizeGradients[1].getFactor();
                }
            }
            if (this.preWarmCycles) {
                if (this.emitter instanceof BABYLON.AbstractMesh) {
                    this.emitter.computeWorldMatrix(true);
                }
                var noiseTextureAsProcedural_1 = this.noiseTexture;
                if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
                    noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
                        setTimeout(function () {
                            for (var index = 0; index < _this.preWarmCycles; index++) {
                                _this.animate(true);
                                noiseTextureAsProcedural_1.render();
                            }
                        });
                    });
                }
                else {
                    for (var index = 0; index < this.preWarmCycles; index++) {
                        this.animate(true);
                    }
                }
            }
            // Animations
            if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
                this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
            }
        };
        /**
         * Stops the particle system.
         * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. the default value is true.
         */
        ParticleSystem.prototype.stop = function (stopSubEmitters) {
            if (stopSubEmitters === void 0) { stopSubEmitters = true; }
            this._stopped = true;
            if (stopSubEmitters) {
                this._stopSubEmitters();
            }
        };
        // animation sheet
        /**
         * Remove all active particles
         */
        ParticleSystem.prototype.reset = function () {
            this._stockParticles = [];
            this._particles = [];
        };
        /**
         * @hidden (for internal use only)
         */
        ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
            var offset = index * this._vertexBufferSize;
            this._vertexData[offset++] = particle.position.x;
            this._vertexData[offset++] = particle.position.y;
            this._vertexData[offset++] = particle.position.z;
            this._vertexData[offset++] = particle.color.r;
            this._vertexData[offset++] = particle.color.g;
            this._vertexData[offset++] = particle.color.b;
            this._vertexData[offset++] = particle.color.a;
            this._vertexData[offset++] = particle.angle;
            this._vertexData[offset++] = particle.scale.x * particle.size;
            this._vertexData[offset++] = particle.scale.y * particle.size;
            if (this._isAnimationSheetEnabled) {
                this._vertexData[offset++] = particle.cellIndex;
            }
            if (!this._isBillboardBased) {
                if (particle._initialDirection) {
                    this._vertexData[offset++] = particle._initialDirection.x;
                    this._vertexData[offset++] = particle._initialDirection.y;
                    this._vertexData[offset++] = particle._initialDirection.z;
                }
                else {
                    this._vertexData[offset++] = particle.direction.x;
                    this._vertexData[offset++] = particle.direction.y;
                    this._vertexData[offset++] = particle.direction.z;
                }
            }
            else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
                this._vertexData[offset++] = particle.direction.x;
                this._vertexData[offset++] = particle.direction.y;
                this._vertexData[offset++] = particle.direction.z;
            }
            if (this._useRampGradients) {
                this._vertexData[offset++] = particle.remapData.x;
                this._vertexData[offset++] = particle.remapData.y;
                this._vertexData[offset++] = particle.remapData.z;
                this._vertexData[offset++] = particle.remapData.w;
            }
            if (!this._useInstancing) {
                if (this._isAnimationSheetEnabled) {
                    if (offsetX === 0) {
                        offsetX = this._epsilon;
                    }
                    else if (offsetX === 1) {
                        offsetX = 1 - this._epsilon;
                    }
                    if (offsetY === 0) {
                        offsetY = this._epsilon;
                    }
                    else if (offsetY === 1) {
                        offsetY = 1 - this._epsilon;
                    }
                }
                this._vertexData[offset++] = offsetX;
                this._vertexData[offset++] = offsetY;
            }
        };
        ParticleSystem.prototype._stopSubEmitters = function () {
            if (!this.activeSubSystems) {
                return;
            }
            this.activeSubSystems.forEach(function (subSystem) {
                subSystem.stop(true);
            });
            this.activeSubSystems = new Array();
        };
        ParticleSystem.prototype._removeFromRoot = function () {
            if (!this._rootParticleSystem) {
                return;
            }
            var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
            if (index !== -1) {
                this._rootParticleSystem.activeSubSystems.splice(index, 1);
            }
            this._rootParticleSystem = null;
        };
        // End of sub system methods
        ParticleSystem.prototype._update = function (newParticles) {
            var _this = this;
            // Update current
            this._alive = this._particles.length > 0;
            if (this.emitter.position) {
                var emitterMesh = this.emitter;
                this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
            }
            else {
                var emitterPosition = this.emitter;
                this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
            }
            this.updateFunction(this._particles);
            // Add new ones
            var particle;
            var _loop_2 = function () {
                if (this_1._particles.length === this_1._capacity) {
                    return "break";
                }
                particle = this_1._createParticle();
                this_1._particles.push(particle);
                // Emitter
                var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
                if (this_1.startPositionFunction) {
                    this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
                }
                else {
                    this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
                }
                if (this_1.startDirectionFunction) {
                    this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
                }
                else {
                    this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
                }
                if (emitPower === 0) {
                    if (!particle._initialDirection) {
                        particle._initialDirection = particle.direction.clone();
                    }
                    else {
                        particle._initialDirection.copyFrom(particle.direction);
                    }
                }
                else {
                    particle._initialDirection = null;
                }
                particle.direction.scaleInPlace(emitPower);
                // Life time
                if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
                    var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
                    BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
                        var factorGradient1 = currentGradient;
                        var factorGradient2 = nextGradient;
                        var lifeTime1 = factorGradient1.getFactor();
                        var lifeTime2 = factorGradient2.getFactor();
                        var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
                        particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
                    });
                }
                else {
                    particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
                }
                // Size
                if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
                    particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
                }
                else {
                    particle._currentSizeGradient = this_1._sizeGradients[0];
                    particle._currentSize1 = particle._currentSizeGradient.getFactor();
                    particle.size = particle._currentSize1;
                    if (this_1._sizeGradients.length > 1) {
                        particle._currentSize2 = this_1._sizeGradients[1].getFactor();
                    }
                    else {
                        particle._currentSize2 = particle._currentSize1;
                    }
                }
                // Size and scale
                particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
                // Adjust scale by start size
                if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
                    var ratio = this_1._actualFrame / this_1.targetStopDuration;
                    BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
                        if (currentGradient !== _this._currentStartSizeGradient) {
                            _this._currentStartSize1 = _this._currentStartSize2;
                            _this._currentStartSize2 = nextGradient.getFactor();
                            _this._currentStartSizeGradient = currentGradient;
                        }
                        var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
                        particle.scale.scaleInPlace(value);
                    });
                }
                // Angle
                if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
                    particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
                }
                else {
                    particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
                    particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
                    particle._currentAngularSpeed1 = particle.angularSpeed;
                    if (this_1._angularSpeedGradients.length > 1) {
                        particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
                    }
                    else {
                        particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
                    }
                }
                particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
                // Velocity
                if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
                    particle._currentVelocityGradient = this_1._velocityGradients[0];
                    particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
                    if (this_1._velocityGradients.length > 1) {
                        particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
                    }
                    else {
                        particle._currentVelocity2 = particle._currentVelocity1;
                    }
                }
                // Limit velocity
                if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
                    particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
                    particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
                    if (this_1._limitVelocityGradients.length > 1) {
                        particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
                    }
                    else {
                        particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
                    }
                }
                // Drag
                if (this_1._dragGradients && this_1._dragGradients.length > 0) {
                    particle._currentDragGradient = this_1._dragGradients[0];
                    particle._currentDrag1 = particle._currentDragGradient.getFactor();
                    if (this_1._dragGradients.length > 1) {
                        particle._currentDrag2 = this_1._dragGradients[1].getFactor();
                    }
                    else {
                        particle._currentDrag2 = particle._currentDrag1;
                    }
                }
                // Color
                if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
                    step = BABYLON.Scalar.RandomRange(0, 1.0);
                    BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
                    this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
                    this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
                }
                else {
                    particle._currentColorGradient = this_1._colorGradients[0];
                    particle._currentColorGradient.getColorToRef(particle.color);
                    particle._currentColor1.copyFrom(particle.color);
                    if (this_1._colorGradients.length > 1) {
                        this_1._colorGradients[1].getColorToRef(particle._currentColor2);
                    }
                    else {
                        particle._currentColor2.copyFrom(particle.color);
                    }
                }
                // Sheet
                if (this_1._isAnimationSheetEnabled) {
                    particle._initialStartSpriteCellID = this_1.startSpriteCellID;
                    particle._initialEndSpriteCellID = this_1.endSpriteCellID;
                }
                // Inherited Velocity
                particle.direction.addInPlace(this_1._inheritedVelocityOffset);
                // Ramp
                if (this_1._useRampGradients) {
                    particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
                }
                // Noise texture coordinates
                if (this_1.noiseTexture) {
                    if (particle._randomNoiseCoordinates1) {
                        particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
                        particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
                    }
                    else {
                        particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
                        particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
                    }
                }
                // Update the position of the attached sub-emitters to match their attached particle
                particle._inheritParticleInfoToSubEmitters();
            };
            var this_1 = this, step;
            for (var index = 0; index < newParticles; index++) {
                var state_1 = _loop_2();
                if (state_1 === "break")
                    break;
            }
        };
        /** @hidden */
        ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
            if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
            if (isBillboardBased === void 0) { isBillboardBased = false; }
            if (useRampGradients === void 0) { useRampGradients = false; }
            var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
            if (isAnimationSheetEnabled) {
                attributeNamesOrOptions.push("cellIndex");
            }
            if (!isBillboardBased) {
                attributeNamesOrOptions.push("direction");
            }
            if (useRampGradients) {
                attributeNamesOrOptions.push("remapData");
            }
            return attributeNamesOrOptions;
        };
        /** @hidden */
        ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
            if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
            var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
            if (isAnimationSheetEnabled) {
                effectCreationOption.push("particlesInfos");
            }
            return effectCreationOption;
        };
        /** @hidden */
        ParticleSystem.prototype._getEffect = function (blendMode) {
            if (this._customEffect) {
                return this._customEffect;
            }
            var defines = [];
            if (this._scene.clipPlane) {
                defines.push("#define CLIPPLANE");
            }
            if (this._scene.clipPlane2) {
                defines.push("#define CLIPPLANE2");
            }
            if (this._scene.clipPlane3) {
                defines.push("#define CLIPPLANE3");
            }
            if (this._scene.clipPlane4) {
                defines.push("#define CLIPPLANE4");
            }
            if (this._isAnimationSheetEnabled) {
                defines.push("#define ANIMATESHEET");
            }
            if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
                defines.push("#define BLENDMULTIPLYMODE");
            }
            if (this._useRampGradients) {
                defines.push("#define RAMPGRADIENT");
            }
            if (this._isBillboardBased) {
                defines.push("#define BILLBOARD");
                switch (this.billboardMode) {
                    case ParticleSystem.BILLBOARDMODE_Y:
                        defines.push("#define BILLBOARDY");
                        break;
                    case ParticleSystem.BILLBOARDMODE_STRETCHED:
                        defines.push("#define BILLBOARDSTRETCHED");
                        break;
                    case ParticleSystem.BILLBOARDMODE_ALL:
                    default:
                        break;
                }
            }
            if (this._imageProcessingConfiguration) {
                this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
                defines.push(this._imageProcessingConfigurationDefines.toString());
            }
            // Effect
            var join = defines.join("\n");
            if (this._cachedDefines !== join) {
                this._cachedDefines = join;
                var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
                var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
                var samplers = ["diffuseSampler", "rampSampler"];
                if (BABYLON.ImageProcessingConfiguration) {
                    BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
                    BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
                }
                this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
            }
            return this._effect;
        };
        /**
         * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
         * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
         */
        ParticleSystem.prototype.animate = function (preWarmOnly) {
            var _this = this;
            if (preWarmOnly === void 0) { preWarmOnly = false; }
            if (!this._started) {
                return;
            }
            if (!preWarmOnly) {
                // Check
                if (!this.isReady()) {
                    return;
                }
                if (this._currentRenderId === this._scene.getRenderId()) {
                    return;
                }
                this._currentRenderId = this._scene.getRenderId();
            }
            this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
            // Determine the number of particles we need to create
            var newParticles;
            if (this.manualEmitCount > -1) {
                newParticles = this.manualEmitCount;
                this._newPartsExcess = 0;
                this.manualEmitCount = 0;
            }
            else {
                var rate_1 = this.emitRate;
                if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
                    var ratio = this._actualFrame / this.targetStopDuration;
                    BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
                        if (currentGradient !== _this._currentEmitRateGradient) {
                            _this._currentEmitRate1 = _this._currentEmitRate2;
                            _this._currentEmitRate2 = nextGradient.getFactor();
                            _this._currentEmitRateGradient = currentGradient;
                        }
                        rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
                    });
                }
                newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
                this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
            }
            if (this._newPartsExcess > 1.0) {
                newParticles += this._newPartsExcess >> 0;
                this._newPartsExcess -= this._newPartsExcess >> 0;
            }
            this._alive = false;
            if (!this._stopped) {
                this._actualFrame += this._scaledUpdateSpeed;
                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
                    this.stop();
                }
            }
            else {
                newParticles = 0;
            }
            this._update(newParticles);
            // Stopped?
            if (this._stopped) {
                if (!this._alive) {
                    this._started = false;
                    if (this.onAnimationEnd) {
                        this.onAnimationEnd();
                    }
                    if (this.disposeOnStop) {
                        this._scene._toBeDisposed.push(this);
                    }
                }
            }
            if (!preWarmOnly) {
                // Update VBO
                var offset = 0;
                for (var index = 0; index < this._particles.length; index++) {
                    var particle = this._particles[index];
                    this._appendParticleVertices(offset, particle);
                    offset += this._useInstancing ? 1 : 4;
                }
                if (this._vertexBuffer) {
                    this._vertexBuffer.update(this._vertexData);
                }
            }
            if (this.manualEmitCount === 0 && this.disposeOnStop) {
                this.stop();
            }
        };
        ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
            this._appendParticleVertex(offset++, particle, 0, 0);
            if (!this._useInstancing) {
                this._appendParticleVertex(offset++, particle, 1, 0);
                this._appendParticleVertex(offset++, particle, 1, 1);
                this._appendParticleVertex(offset++, particle, 0, 1);
            }
        };
        /**
         * Rebuilds the particle system.
         */
        ParticleSystem.prototype.rebuild = function () {
            this._createIndexBuffer();
            if (this._vertexBuffer) {
                this._vertexBuffer._rebuild();
            }
        };
        /**
         * Is this system ready to be used/rendered
         * @return true if the system is ready
         */
        ParticleSystem.prototype.isReady = function () {
            if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
                return false;
            }
            if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
                if (!this._getEffect(this.blendMode).isReady()) {
                    return false;
                }
            }
            else {
                if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
                    return false;
                }
                if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
                    return false;
                }
            }
            return true;
        };
        ParticleSystem.prototype._render = function (blendMode) {
            var effect = this._getEffect(blendMode);
            var engine = this._scene.getEngine();
            // Render
            engine.enableEffect(effect);
            var viewMatrix = this._scene.getViewMatrix();
            effect.setTexture("diffuseSampler", this.particleTexture);
            effect.setMatrix("view", viewMatrix);
            effect.setMatrix("projection", this._scene.getProjectionMatrix());
            if (this._isAnimationSheetEnabled && this.particleTexture) {
                var baseSize = this.particleTexture.getBaseSize();
                effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
            }
            effect.setVector2("translationPivot", this.translationPivot);
            effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
            if (this._isBillboardBased) {
                var camera = this._scene.activeCamera;
                effect.setVector3("eyePosition", camera.globalPosition);
            }
            if (this._rampGradientsTexture) {
                effect.setTexture("rampSampler", this._rampGradientsTexture);
            }
            if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
                var invView = viewMatrix.clone();
                invView.invert();
                effect.setMatrix("invView", invView);
                BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
            }
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
            // image processing
            if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
                this._imageProcessingConfiguration.bind(effect);
            }
            // Draw order
            switch (blendMode) {
                case ParticleSystem.BLENDMODE_ADD:
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
                    break;
                case ParticleSystem.BLENDMODE_ONEONE:
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
                    break;
                case ParticleSystem.BLENDMODE_STANDARD:
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                    break;
                case ParticleSystem.BLENDMODE_MULTIPLY:
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
                    break;
            }
            if (this._useInstancing) {
                engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
            }
            else {
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
            }
            return this._particles.length;
        };
        /**
         * Renders the particle system in its current state.
         * @returns the current number of particles
         */
        ParticleSystem.prototype.render = function () {
            // Check
            if (!this.isReady() || !this._particles.length) {
                return 0;
            }
            var engine = this._scene.getEngine();
            engine.setState(false);
            if (this.forceDepthWrite) {
                engine.setDepthWrite(true);
            }
            var outparticles = 0;
            if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
                outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
            }
            outparticles = this._render(this.blendMode);
            engine.unbindInstanceAttributes();
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            return outparticles;
        };
        /**
         * Disposes the particle system and free the associated resources
         * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
         */
        ParticleSystem.prototype.dispose = function (disposeTexture) {
            if (disposeTexture === void 0) { disposeTexture = true; }
            if (this._vertexBuffer) {
                this._vertexBuffer.dispose();
                this._vertexBuffer = null;
            }
            if (this._spriteBuffer) {
                this._spriteBuffer.dispose();
                this._spriteBuffer = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            if (disposeTexture && this.particleTexture) {
                this.particleTexture.dispose();
                this.particleTexture = null;
            }
            if (disposeTexture && this.noiseTexture) {
                this.noiseTexture.dispose();
                this.noiseTexture = null;
            }
            if (this._rampGradientsTexture) {
                this._rampGradientsTexture.dispose();
                this._rampGradientsTexture = null;
            }
            this._removeFromRoot();
            if (this._subEmitters && this._subEmitters.length) {
                for (var index = 0; index < this._subEmitters.length; index++) {
                    for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
                        var subEmitter = _a[_i];
                        subEmitter.dispose();
                    }
                }
                this._subEmitters = [];
                this.subEmitters = [];
            }
            if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
                this.emitter.dispose(true);
            }
            // Remove from scene
            var index = this._scene.particleSystems.indexOf(this);
            if (index > -1) {
                this._scene.particleSystems.splice(index, 1);
            }
            this._scene._activeParticleSystems.dispose();
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.reset();
        };
        // Clone
        /**
         * Clones the particle system.
         * @param name The name of the cloned object
         * @param newEmitter The new emitter to use
         * @returns the cloned particle system
         */
        ParticleSystem.prototype.clone = function (name, newEmitter) {
            var custom = null;
            var program = null;
            if (this.customShader != null) {
                program = this.customShader;
                var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
                custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
            }
            else if (this._customEffect) {
                custom = this._customEffect;
            }
            var result = new ParticleSystem(name, this._capacity, this._scene, custom);
            result.customShader = program;
            BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
            if (newEmitter === undefined) {
                newEmitter = this.emitter;
            }
            result.noiseTexture = this.noiseTexture;
            result.emitter = newEmitter;
            if (this.particleTexture) {
                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
            }
            // Clone gradients
            if (this._colorGradients) {
                this._colorGradients.forEach(function (v) {
                    result.addColorGradient(v.gradient, v.color1, v.color2);
                });
            }
            if (this._dragGradients) {
                this._dragGradients.forEach(function (v) {
                    result.addDragGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._angularSpeedGradients) {
                this._angularSpeedGradients.forEach(function (v) {
                    result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._emitRateGradients) {
                this._emitRateGradients.forEach(function (v) {
                    result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._lifeTimeGradients) {
                this._lifeTimeGradients.forEach(function (v) {
                    result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._limitVelocityGradients) {
                this._limitVelocityGradients.forEach(function (v) {
                    result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._sizeGradients) {
                this._sizeGradients.forEach(function (v) {
                    result.addSizeGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._startSizeGradients) {
                this._startSizeGradients.forEach(function (v) {
                    result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._velocityGradients) {
                this._velocityGradients.forEach(function (v) {
                    result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._rampGradients) {
                this._rampGradients.forEach(function (v) {
                    result.addRampGradient(v.gradient, v.color);
                });
            }
            if (this._colorRemapGradients) {
                this._colorRemapGradients.forEach(function (v) {
                    result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (this._alphaRemapGradients) {
                this._alphaRemapGradients.forEach(function (v) {
                    result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
                });
            }
            if (!this.preventAutoStart) {
                result.start();
            }
            return result;
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        ParticleSystem.prototype.serialize = function () {
            var serializationObject = {};
            ParticleSystem._Serialize(serializationObject, this);
            serializationObject.textureMask = this.textureMask.asArray();
            serializationObject.customShader = this.customShader;
            serializationObject.preventAutoStart = this.preventAutoStart;
            // SubEmitters
            if (this.subEmitters) {
                serializationObject.subEmitters = [];
                if (!this._subEmitters) {
                    this._prepareSubEmitterInternalArray();
                }
                for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
                    var subs = _a[_i];
                    var cell = [];
                    for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
                        var sub = subs_1[_b];
                        cell.push(sub.serialize());
                    }
                    serializationObject.subEmitters.push(cell);
                }
            }
            return serializationObject;
        };
        /** @hidden */
        ParticleSystem._Serialize = function (serializationObject, particleSystem) {
            serializationObject.name = particleSystem.name;
            serializationObject.id = particleSystem.id;
            serializationObject.capacity = particleSystem.getCapacity();
            // Emitter
            if (particleSystem.emitter.position) {
                var emitterMesh = particleSystem.emitter;
                serializationObject.emitterId = emitterMesh.id;
            }
            else {
                var emitterPosition = particleSystem.emitter;
                serializationObject.emitter = emitterPosition.asArray();
            }
            // Emitter
            if (particleSystem.particleEmitterType) {
                serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
            }
            if (particleSystem.particleTexture) {
                serializationObject.textureName = particleSystem.particleTexture.name;
                serializationObject.invertY = particleSystem.particleTexture._invertY;
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
            serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
            serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
            serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
            serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
            // Particle system
            serializationObject.startDelay = particleSystem.startDelay;
            serializationObject.renderingGroupId = particleSystem.renderingGroupId;
            serializationObject.isBillboardBased = particleSystem.isBillboardBased;
            serializationObject.billboardMode = particleSystem.billboardMode;
            serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
            serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
            serializationObject.minSize = particleSystem.minSize;
            serializationObject.maxSize = particleSystem.maxSize;
            serializationObject.minScaleX = particleSystem.minScaleX;
            serializationObject.maxScaleX = particleSystem.maxScaleX;
            serializationObject.minScaleY = particleSystem.minScaleY;
            serializationObject.maxScaleY = particleSystem.maxScaleY;
            serializationObject.minEmitPower = particleSystem.minEmitPower;
            serializationObject.maxEmitPower = particleSystem.maxEmitPower;
            serializationObject.minLifeTime = particleSystem.minLifeTime;
            serializationObject.maxLifeTime = particleSystem.maxLifeTime;
            serializationObject.emitRate = particleSystem.emitRate;
            serializationObject.gravity = particleSystem.gravity.asArray();
            serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
            serializationObject.color1 = particleSystem.color1.asArray();
            serializationObject.color2 = particleSystem.color2.asArray();
            serializationObject.colorDead = particleSystem.colorDead.asArray();
            serializationObject.updateSpeed = particleSystem.updateSpeed;
            serializationObject.targetStopDuration = particleSystem.targetStopDuration;
            serializationObject.blendMode = particleSystem.blendMode;
            serializationObject.preWarmCycles = particleSystem.preWarmCycles;
            serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
            serializationObject.minInitialRotation = particleSystem.minInitialRotation;
            serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
            serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
            serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
            serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
            serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
            serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
            serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
            serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
            var colorGradients = particleSystem.getColorGradients();
            if (colorGradients) {
                serializationObject.colorGradients = [];
                for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
                    var colorGradient = colorGradients_1[_i];
                    var serializedGradient = {
                        gradient: colorGradient.gradient,
                        color1: colorGradient.color1.asArray()
                    };
                    if (colorGradient.color2) {
                        serializedGradient.color2 = colorGradient.color2.asArray();
                    }
                    serializationObject.colorGradients.push(serializedGradient);
                }
            }
            var rampGradients = particleSystem.getRampGradients();
            if (rampGradients) {
                serializationObject.rampGradients = [];
                for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
                    var rampGradient = rampGradients_1[_a];
                    var serializedGradient = {
                        gradient: rampGradient.gradient,
                        color: rampGradient.color.asArray()
                    };
                    serializationObject.rampGradients.push(serializedGradient);
                }
                serializationObject.useRampGradients = particleSystem.useRampGradients;
            }
            var colorRemapGradients = particleSystem.getColorRemapGradients();
            if (colorRemapGradients) {
                serializationObject.colorRemapGradients = [];
                for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
                    var colorRemapGradient = colorRemapGradients_1[_b];
                    var serializedGradient = {
                        gradient: colorRemapGradient.gradient,
                        factor1: colorRemapGradient.factor1
                    };
                    if (colorRemapGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = colorRemapGradient.factor2;
                    }
                    serializationObject.colorRemapGradients.push(serializedGradient);
                }
            }
            var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
            if (alphaRemapGradients) {
                serializationObject.alphaRemapGradients = [];
                for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
                    var alphaRemapGradient = alphaRemapGradients_1[_c];
                    var serializedGradient = {
                        gradient: alphaRemapGradient.gradient,
                        factor1: alphaRemapGradient.factor1
                    };
                    if (alphaRemapGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = alphaRemapGradient.factor2;
                    }
                    serializationObject.alphaRemapGradients.push(serializedGradient);
                }
            }
            var sizeGradients = particleSystem.getSizeGradients();
            if (sizeGradients) {
                serializationObject.sizeGradients = [];
                for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
                    var sizeGradient = sizeGradients_1[_d];
                    var serializedGradient = {
                        gradient: sizeGradient.gradient,
                        factor1: sizeGradient.factor1
                    };
                    if (sizeGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = sizeGradient.factor2;
                    }
                    serializationObject.sizeGradients.push(serializedGradient);
                }
            }
            var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
            if (angularSpeedGradients) {
                serializationObject.angularSpeedGradients = [];
                for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
                    var angularSpeedGradient = angularSpeedGradients_1[_e];
                    var serializedGradient = {
                        gradient: angularSpeedGradient.gradient,
                        factor1: angularSpeedGradient.factor1
                    };
                    if (angularSpeedGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = angularSpeedGradient.factor2;
                    }
                    serializationObject.angularSpeedGradients.push(serializedGradient);
                }
            }
            var velocityGradients = particleSystem.getVelocityGradients();
            if (velocityGradients) {
                serializationObject.velocityGradients = [];
                for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
                    var velocityGradient = velocityGradients_1[_f];
                    var serializedGradient = {
                        gradient: velocityGradient.gradient,
                        factor1: velocityGradient.factor1
                    };
                    if (velocityGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = velocityGradient.factor2;
                    }
                    serializationObject.velocityGradients.push(serializedGradient);
                }
            }
            var dragGradients = particleSystem.getDragGradients();
            if (dragGradients) {
                serializationObject.dragyGradients = [];
                for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
                    var dragGradient = dragGradients_1[_g];
                    var serializedGradient = {
                        gradient: dragGradient.gradient,
                        factor1: dragGradient.factor1
                    };
                    if (dragGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = dragGradient.factor2;
                    }
                    serializationObject.dragGradients.push(serializedGradient);
                }
            }
            var emitRateGradients = particleSystem.getEmitRateGradients();
            if (emitRateGradients) {
                serializationObject.emitRateGradients = [];
                for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
                    var emitRateGradient = emitRateGradients_1[_h];
                    var serializedGradient = {
                        gradient: emitRateGradient.gradient,
                        factor1: emitRateGradient.factor1
                    };
                    if (emitRateGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = emitRateGradient.factor2;
                    }
                    serializationObject.emitRateGradients.push(serializedGradient);
                }
            }
            var startSizeGradients = particleSystem.getStartSizeGradients();
            if (startSizeGradients) {
                serializationObject.startSizeGradients = [];
                for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
                    var startSizeGradient = startSizeGradients_1[_j];
                    var serializedGradient = {
                        gradient: startSizeGradient.gradient,
                        factor1: startSizeGradient.factor1
                    };
                    if (startSizeGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = startSizeGradient.factor2;
                    }
                    serializationObject.startSizeGradients.push(serializedGradient);
                }
            }
            var lifeTimeGradients = particleSystem.getLifeTimeGradients();
            if (lifeTimeGradients) {
                serializationObject.lifeTimeGradients = [];
                for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
                    var lifeTimeGradient = lifeTimeGradients_1[_k];
                    var serializedGradient = {
                        gradient: lifeTimeGradient.gradient,
                        factor1: lifeTimeGradient.factor1
                    };
                    if (lifeTimeGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = lifeTimeGradient.factor2;
                    }
                    serializationObject.lifeTimeGradients.push(serializedGradient);
                }
            }
            var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
            if (limitVelocityGradients) {
                serializationObject.limitVelocityGradients = [];
                for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
                    var limitVelocityGradient = limitVelocityGradients_1[_l];
                    var serializedGradient = {
                        gradient: limitVelocityGradient.gradient,
                        factor1: limitVelocityGradient.factor1
                    };
                    if (limitVelocityGradient.factor2 !== undefined) {
                        serializedGradient.factor2 = limitVelocityGradient.factor2;
                    }
                    serializationObject.limitVelocityGradients.push(serializedGradient);
                }
                serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
            }
            if (particleSystem.noiseTexture) {
                serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
            }
        };
        /** @hidden */
        ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
            // Texture
            if (parsedParticleSystem.textureName) {
                particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
                particleSystem.particleTexture.name = parsedParticleSystem.textureName;
            }
            // Emitter
            if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
                particleSystem.emitter = BABYLON.Vector3.Zero();
            }
            else if (parsedParticleSystem.emitterId) {
                particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
            }
            else {
                particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
            }
            // Misc.
            if (parsedParticleSystem.renderingGroupId !== undefined) {
                particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
            }
            if (parsedParticleSystem.isBillboardBased !== undefined) {
                particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
            }
            if (parsedParticleSystem.billboardMode !== undefined) {
                particleSystem.billboardMode = parsedParticleSystem.billboardMode;
            }
            // Animations
            if (parsedParticleSystem.animations) {
                for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
                    var parsedAnimation = parsedParticleSystem.animations[animationIndex];
                    particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
                particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
                particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
                particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
                particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
            }
            if (parsedParticleSystem.autoAnimate) {
                scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
            }
            // Particle system
            particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
            particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
            particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
            particleSystem.minSize = parsedParticleSystem.minSize;
            particleSystem.maxSize = parsedParticleSystem.maxSize;
            if (parsedParticleSystem.minScaleX) {
                particleSystem.minScaleX = parsedParticleSystem.minScaleX;
                particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
                particleSystem.minScaleY = parsedParticleSystem.minScaleY;
                particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
            }
            if (parsedParticleSystem.preWarmCycles !== undefined) {
                particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
                particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
            }
            if (parsedParticleSystem.minInitialRotation !== undefined) {
                particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
                particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
            }
            particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
            particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
            particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
            particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
            particleSystem.emitRate = parsedParticleSystem.emitRate;
            particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
            if (parsedParticleSystem.noiseStrength) {
                particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
            }
            particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
            particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
            particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
            particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
            particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
            particleSystem.blendMode = parsedParticleSystem.blendMode;
            if (parsedParticleSystem.colorGradients) {
                for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
                    var colorGradient = _a[_i];
                    particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
                }
            }
            if (parsedParticleSystem.rampGradients) {
                for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
                    var rampGradient = _c[_b];
                    particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
                }
                particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
            }
            if (parsedParticleSystem.colorRemapGradients) {
                for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
                    var colorRemapGradient = _e[_d];
                    particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
                }
            }
            if (parsedParticleSystem.alphaRemapGradients) {
                for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
                    var alphaRemapGradient = _g[_f];
                    particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
                }
            }
            if (parsedParticleSystem.sizeGradients) {
                for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
                    var sizeGradient = _j[_h];
                    particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
                }
            }
            if (parsedParticleSystem.sizeGradients) {
                for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
                    var sizeGradient = _l[_k];
                    particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
                }
            }
            if (parsedParticleSystem.angularSpeedGradients) {
                for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
                    var angularSpeedGradient = _o[_m];
                    particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
                }
            }
            if (parsedParticleSystem.velocityGradients) {
                for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
                    var velocityGradient = _q[_p];
                    particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
                }
            }
            if (parsedParticleSystem.dragGradients) {
                for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
                    var dragGradient = _s[_r];
                    particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
                }
            }
            if (parsedParticleSystem.emitRateGradients) {
                for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
                    var emitRateGradient = _u[_t];
                    particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
                }
            }
            if (parsedParticleSystem.startSizeGradients) {
                for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
                    var startSizeGradient = _w[_v];
                    particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
                }
            }
            if (parsedParticleSystem.lifeTimeGradients) {
                for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
                    var lifeTimeGradient = _y[_x];
                    particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
                }
            }
            if (parsedParticleSystem.limitVelocityGradients) {
                for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
                    var limitVelocityGradient = _0[_z];
                    particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
                }
                particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
            }
            if (parsedParticleSystem.noiseTexture) {
                particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
            }
            // Emitter
            var emitterType;
            if (parsedParticleSystem.particleEmitterType) {
                switch (parsedParticleSystem.particleEmitterType.type) {
                    case "SphereParticleEmitter":
                        emitterType = new BABYLON.SphereParticleEmitter();
                        break;
                    case "SphereDirectedParticleEmitter":
                        emitterType = new BABYLON.SphereDirectedParticleEmitter();
                        break;
                    case "ConeEmitter":
                    case "ConeParticleEmitter":
                        emitterType = new BABYLON.ConeParticleEmitter();
                        break;
                    case "CylinderParticleEmitter":
                        emitterType = new BABYLON.CylinderParticleEmitter();
                        break;
                    case "HemisphericParticleEmitter":
                        emitterType = new BABYLON.HemisphericParticleEmitter();
                        break;
                    case "BoxEmitter":
                    case "BoxParticleEmitter":
                    default:
                        emitterType = new BABYLON.BoxParticleEmitter();
                        break;
                }
                emitterType.parse(parsedParticleSystem.particleEmitterType);
            }
            else {
                emitterType = new BABYLON.BoxParticleEmitter();
                emitterType.parse(parsedParticleSystem);
            }
            particleSystem.particleEmitterType = emitterType;
            // Animation sheet
            particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
            particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
            particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
            particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
            particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
            particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
        };
        /**
         * Parses a JSON object to create a particle system.
         * @param parsedParticleSystem The JSON object to parse
         * @param scene The scene to create the particle system in
         * @param rootUrl The root url to use to load external dependencies like texture
         * @param doNotStart Ignore the preventAutoStart attribute and does not start
         * @returns the Parsed particle system
         */
        ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
            if (doNotStart === void 0) { doNotStart = false; }
            var name = parsedParticleSystem.name;
            var custom = null;
            var program = null;
            if (parsedParticleSystem.customShader) {
                program = parsedParticleSystem.customShader;
                var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
                custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
            }
            var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
            particleSystem.customShader = program;
            if (parsedParticleSystem.id) {
                particleSystem.id = parsedParticleSystem.id;
            }
            // SubEmitters
            if (parsedParticleSystem.subEmitters) {
                particleSystem.subEmitters = [];
                for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
                    var cell = _a[_i];
                    var cellArray = [];
                    for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
                        var sub = cell_1[_b];
                        cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
                    }
                    particleSystem.subEmitters.push(cellArray);
                }
            }
            ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
            particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
            // Auto start
            if (parsedParticleSystem.preventAutoStart) {
                particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
            }
            if (!doNotStart && !particleSystem.preventAutoStart) {
                particleSystem.start();
            }
            return particleSystem;
        };
        /**
         * Billboard mode will only apply to Y axis
         */
        ParticleSystem.BILLBOARDMODE_Y = 2;
        /**
         * Billboard mode will apply to all axes
         */
        ParticleSystem.BILLBOARDMODE_ALL = 7;
        /**
         * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
         */
        ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
        return ParticleSystem;
    }(BABYLON.BaseParticleSystem));
    BABYLON.ParticleSystem = ParticleSystem;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.particleSystem.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Particle emitter emitting particles from the inside of a box.
     * It emits the particles randomly between 2 given directions.
     */
    var BoxParticleEmitter = /** @class */ (function () {
        /**
         * Creates a new instance BoxParticleEmitter
         */
        function BoxParticleEmitter() {
            /**
             * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
             */
            this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
            /**
             * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
             */
            this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
            /**
             * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
             */
            this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
            /**
             * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
             */
            this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
            var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
            var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
            BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
        };
        /**
         * Called by the particle System when the position is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param positionToUpdate is the position vector to update with the result
         * @param particle is the particle we are computed the position for
         */
        BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
            var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
            var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
            var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        BoxParticleEmitter.prototype.clone = function () {
            var newOne = new BoxParticleEmitter();
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        BoxParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setVector3("direction1", this.direction1);
            effect.setVector3("direction2", this.direction2);
            effect.setVector3("minEmitBox", this.minEmitBox);
            effect.setVector3("maxEmitBox", this.maxEmitBox);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        BoxParticleEmitter.prototype.getEffectDefines = function () {
            return "#define BOXEMITTER";
        };
        /**
         * Returns the string "BoxParticleEmitter"
         * @returns a string containing the class name
         */
        BoxParticleEmitter.prototype.getClassName = function () {
            return "BoxParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        BoxParticleEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.getClassName();
            serializationObject.direction1 = this.direction1.asArray();
            serializationObject.direction2 = this.direction2.asArray();
            serializationObject.minEmitBox = this.minEmitBox.asArray();
            serializationObject.maxEmitBox = this.maxEmitBox.asArray();
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        BoxParticleEmitter.prototype.parse = function (serializationObject) {
            BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
            BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
            BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
            BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
        };
        return BoxParticleEmitter;
    }());
    BABYLON.BoxParticleEmitter = BoxParticleEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boxParticleEmitter.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Particle emitter emitting particles from the inside of a cylinder.
     * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
     */
    var CylinderParticleEmitter = /** @class */ (function () {
        /**
        * Creates a new instance CylinderParticleEmitter
        * @param radius the radius of the emission cylinder (1 by default)
        * @param height the height of the emission cylinder (1 by default)
        * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
        * @param directionRandomizer defines how much to randomize the particle direction [0-1]
        */
        function CylinderParticleEmitter(
        /**
         * The radius of the emission cylinder.
         */
        radius, 
        /**
         * The height of the emission cylinder.
         */
        height, 
        /**
         * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
         */
        radiusRange, 
        /**
         * How much to randomize the particle direction [0-1].
         */
        directionRandomizer) {
            if (radius === void 0) { radius = 1; }
            if (height === void 0) { height = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            if (directionRandomizer === void 0) { directionRandomizer = 0; }
            this.radius = radius;
            this.height = height;
            this.radiusRange = radiusRange;
            this.directionRandomizer = directionRandomizer;
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
            var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
            var angle = Math.atan2(direction.x, direction.z);
            angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
            direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
            direction.x = Math.sin(angle);
            direction.z = Math.cos(angle);
            direction.normalize();
            BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
        };
        /**
         * Called by the particle System when the position is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param positionToUpdate is the position vector to update with the result
         * @param particle is the particle we are computed the position for
         */
        CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
            var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
            var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
            // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
            var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
            var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
            var xPos = positionRadius * Math.cos(angle);
            var zPos = positionRadius * Math.sin(angle);
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        CylinderParticleEmitter.prototype.clone = function () {
            var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        CylinderParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setFloat("radius", this.radius);
            effect.setFloat("height", this.height);
            effect.setFloat("radiusRange", this.radiusRange);
            effect.setFloat("directionRandomizer", this.directionRandomizer);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        CylinderParticleEmitter.prototype.getEffectDefines = function () {
            return "#define CYLINDEREMITTER";
        };
        /**
         * Returns the string "CylinderParticleEmitter"
         * @returns a string containing the class name
         */
        CylinderParticleEmitter.prototype.getClassName = function () {
            return "CylinderParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        CylinderParticleEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.getClassName();
            serializationObject.radius = this.radius;
            serializationObject.height = this.height;
            serializationObject.radiusRange = this.radiusRange;
            serializationObject.directionRandomizer = this.directionRandomizer;
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        CylinderParticleEmitter.prototype.parse = function (serializationObject) {
            this.radius = serializationObject.radius;
            this.height = serializationObject.height;
            this.radiusRange = serializationObject.radiusRange;
            this.directionRandomizer = serializationObject.directionRandomizer;
        };
        return CylinderParticleEmitter;
    }());
    BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
    /**
     * Particle emitter emitting particles from the inside of a cylinder.
     * It emits the particles randomly between two vectors.
     */
    var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
        __extends(CylinderDirectedParticleEmitter, _super);
        /**
         * Creates a new instance CylinderDirectedParticleEmitter
         * @param radius the radius of the emission cylinder (1 by default)
         * @param height the height of the emission cylinder (1 by default)
         * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
         * @param direction1 the min limit of the emission direction (up vector by default)
         * @param direction2 the max limit of the emission direction (up vector by default)
         */
        function CylinderDirectedParticleEmitter(radius, height, radiusRange, 
        /**
         * The min limit of the emission direction.
         */
        direction1, 
        /**
         * The max limit of the emission direction.
         */
        direction2) {
            if (radius === void 0) { radius = 1; }
            if (height === void 0) { height = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
            if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
            var _this = _super.call(this, radius, height, radiusRange) || this;
            _this.direction1 = direction1;
            _this.direction2 = direction2;
            return _this;
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
            var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
            var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
            BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        CylinderDirectedParticleEmitter.prototype.clone = function () {
            var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setFloat("radius", this.radius);
            effect.setFloat("height", this.height);
            effect.setFloat("radiusRange", this.radiusRange);
            effect.setVector3("direction1", this.direction1);
            effect.setVector3("direction2", this.direction2);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
            return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
        };
        /**
         * Returns the string "CylinderDirectedParticleEmitter"
         * @returns a string containing the class name
         */
        CylinderDirectedParticleEmitter.prototype.getClassName = function () {
            return "CylinderDirectedParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        CylinderDirectedParticleEmitter.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.direction1 = this.direction1.asArray();
            serializationObject.direction2 = this.direction2.asArray();
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
            _super.prototype.parse.call(this, serializationObject);
            this.direction1.copyFrom(serializationObject.direction1);
            this.direction2.copyFrom(serializationObject.direction2);
        };
        return CylinderDirectedParticleEmitter;
    }(CylinderParticleEmitter));
    BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.cylinderParticleEmitter.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Particle emitter emitting particles from the inside of a cone.
     * It emits the particles alongside the cone volume from the base to the particle.
     * The emission direction might be randomized.
     */
    var ConeParticleEmitter = /** @class */ (function () {
        /**
         * Creates a new instance ConeParticleEmitter
         * @param radius the radius of the emission cone (1 by default)
         * @param angles the cone base angle (PI by default)
         * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
         */
        function ConeParticleEmitter(radius, angle, 
        /** defines how much to randomize the particle direction [0-1] (default is 0) */
        directionRandomizer) {
            if (radius === void 0) { radius = 1; }
            if (angle === void 0) { angle = Math.PI; }
            if (directionRandomizer === void 0) { directionRandomizer = 0; }
            this.directionRandomizer = directionRandomizer;
            /**
             * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
             */
            this.radiusRange = 1;
            /**
             * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
             */
            this.heightRange = 1;
            /**
             * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
             */
            this.emitFromSpawnPointOnly = false;
            this.angle = angle;
            this.radius = radius;
        }
        Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
            /**
             * Gets or sets the radius of the emission cone
             */
            get: function () {
                return this._radius;
            },
            set: function (value) {
                this._radius = value;
                this._buildHeight();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
            /**
             * Gets or sets the angle of the emission cone
             */
            get: function () {
                return this._angle;
            },
            set: function (value) {
                this._angle = value;
                this._buildHeight();
            },
            enumerable: true,
            configurable: true
        });
        ConeParticleEmitter.prototype._buildHeight = function () {
            if (this._angle !== 0) {
                this._height = this._radius / Math.tan(this._angle / 2);
            }
            else {
                this._height = 1;
            }
        };
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            if (Math.abs(Math.cos(this._angle)) === 1.0) {
                BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
            }
            else {
                // measure the direction Vector from the emitter to the particle.
                var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
                var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
                var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
                var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
                direction.x += randX;
                direction.y += randY;
                direction.z += randZ;
                direction.normalize();
                BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
            }
        };
        /**
         * Called by the particle System when the position is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param positionToUpdate is the position vector to update with the result
         * @param particle is the particle we are computed the position for
         */
        ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
            var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
            var h;
            if (!this.emitFromSpawnPointOnly) {
                h = BABYLON.Scalar.RandomRange(0, this.heightRange);
                // Better distribution in a cone at normal angles.
                h = 1 - h * h;
            }
            else {
                h = 0.0001;
            }
            var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
            radius = radius * h;
            var randX = radius * Math.sin(s);
            var randZ = radius * Math.cos(s);
            var randY = h * this._height;
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        ConeParticleEmitter.prototype.clone = function () {
            var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        ConeParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setFloat2("radius", this._radius, this.radiusRange);
            effect.setFloat("coneAngle", this._angle);
            effect.setFloat2("height", this._height, this.heightRange);
            effect.setFloat("directionRandomizer", this.directionRandomizer);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        ConeParticleEmitter.prototype.getEffectDefines = function () {
            var defines = "#define CONEEMITTER";
            if (this.emitFromSpawnPointOnly) {
                defines += "\n#define CONEEMITTERSPAWNPOINT";
            }
            return defines;
        };
        /**
         * Returns the string "ConeParticleEmitter"
         * @returns a string containing the class name
         */
        ConeParticleEmitter.prototype.getClassName = function () {
            return "ConeParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        ConeParticleEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.getClassName();
            serializationObject.radius = this._radius;
            serializationObject.angle = this._angle;
            serializationObject.directionRandomizer = this.directionRandomizer;
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        ConeParticleEmitter.prototype.parse = function (serializationObject) {
            this.radius = serializationObject.radius;
            this.angle = serializationObject.angle;
            this.directionRandomizer = serializationObject.directionRandomizer;
        };
        return ConeParticleEmitter;
    }());
    BABYLON.ConeParticleEmitter = ConeParticleEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.coneParticleEmitter.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Particle emitter emitting particles from the inside of a sphere.
     * It emits the particles alongside the sphere radius. The emission direction might be randomized.
     */
    var SphereParticleEmitter = /** @class */ (function () {
        /**
        * Creates a new instance SphereParticleEmitter
        * @param radius the radius of the emission sphere (1 by default)
        * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
        * @param directionRandomizer defines how much to randomize the particle direction [0-1]
        */
        function SphereParticleEmitter(
        /**
         * The radius of the emission sphere.
         */
        radius, 
        /**
         * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
         */
        radiusRange, 
        /**
         * How much to randomize the particle direction [0-1].
         */
        directionRandomizer) {
            if (radius === void 0) { radius = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            if (directionRandomizer === void 0) { directionRandomizer = 0; }
            this.radius = radius;
            this.radiusRange = radiusRange;
            this.directionRandomizer = directionRandomizer;
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
            var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
            var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
            var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
            direction.x += randX;
            direction.y += randY;
            direction.z += randZ;
            direction.normalize();
            BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
        };
        /**
         * Called by the particle System when the position is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param positionToUpdate is the position vector to update with the result
         * @param particle is the particle we are computed the position for
         */
        SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
            var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
            var v = BABYLON.Scalar.RandomRange(0, 1.0);
            var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
            var theta = Math.acos(2 * v - 1);
            var randX = randRadius * Math.cos(phi) * Math.sin(theta);
            var randY = randRadius * Math.cos(theta);
            var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        SphereParticleEmitter.prototype.clone = function () {
            var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        SphereParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setFloat("radius", this.radius);
            effect.setFloat("radiusRange", this.radiusRange);
            effect.setFloat("directionRandomizer", this.directionRandomizer);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        SphereParticleEmitter.prototype.getEffectDefines = function () {
            return "#define SPHEREEMITTER";
        };
        /**
         * Returns the string "SphereParticleEmitter"
         * @returns a string containing the class name
         */
        SphereParticleEmitter.prototype.getClassName = function () {
            return "SphereParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        SphereParticleEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.getClassName();
            serializationObject.radius = this.radius;
            serializationObject.radiusRange = this.radiusRange;
            serializationObject.directionRandomizer = this.directionRandomizer;
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        SphereParticleEmitter.prototype.parse = function (serializationObject) {
            this.radius = serializationObject.radius;
            this.radiusRange = serializationObject.radiusRange;
            this.directionRandomizer = serializationObject.directionRandomizer;
        };
        return SphereParticleEmitter;
    }());
    BABYLON.SphereParticleEmitter = SphereParticleEmitter;
    /**
     * Particle emitter emitting particles from the inside of a sphere.
     * It emits the particles randomly between two vectors.
     */
    var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
        __extends(SphereDirectedParticleEmitter, _super);
        /**
         * Creates a new instance SphereDirectedParticleEmitter
         * @param radius the radius of the emission sphere (1 by default)
         * @param direction1 the min limit of the emission direction (up vector by default)
         * @param direction2 the max limit of the emission direction (up vector by default)
         */
        function SphereDirectedParticleEmitter(radius, 
        /**
         * The min limit of the emission direction.
         */
        direction1, 
        /**
         * The max limit of the emission direction.
         */
        direction2) {
            if (radius === void 0) { radius = 1; }
            if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
            if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
            var _this = _super.call(this, radius) || this;
            _this.direction1 = direction1;
            _this.direction2 = direction2;
            return _this;
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
            var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
            var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
            BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        SphereDirectedParticleEmitter.prototype.clone = function () {
            var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setFloat("radius", this.radius);
            effect.setFloat("radiusRange", this.radiusRange);
            effect.setVector3("direction1", this.direction1);
            effect.setVector3("direction2", this.direction2);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
            return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
        };
        /**
         * Returns the string "SphereDirectedParticleEmitter"
         * @returns a string containing the class name
         */
        SphereDirectedParticleEmitter.prototype.getClassName = function () {
            return "SphereDirectedParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        SphereDirectedParticleEmitter.prototype.serialize = function () {
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.direction1 = this.direction1.asArray();
            serializationObject.direction2 = this.direction2.asArray();
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
            _super.prototype.parse.call(this, serializationObject);
            this.direction1.copyFrom(serializationObject.direction1);
            this.direction2.copyFrom(serializationObject.direction2);
        };
        return SphereDirectedParticleEmitter;
    }(SphereParticleEmitter));
    BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sphereParticleEmitter.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Particle emitter emitting particles from the inside of a hemisphere.
     * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
     */
    var HemisphericParticleEmitter = /** @class */ (function () {
        /**
        * Creates a new instance HemisphericParticleEmitter
        * @param radius the radius of the emission hemisphere (1 by default)
        * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
        * @param directionRandomizer defines how much to randomize the particle direction [0-1]
        */
        function HemisphericParticleEmitter(
        /**
         * The radius of the emission hemisphere.
         */
        radius, 
        /**
         * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
         */
        radiusRange, 
        /**
         * How much to randomize the particle direction [0-1].
         */
        directionRandomizer) {
            if (radius === void 0) { radius = 1; }
            if (radiusRange === void 0) { radiusRange = 1; }
            if (directionRandomizer === void 0) { directionRandomizer = 0; }
            this.radius = radius;
            this.radiusRange = radiusRange;
            this.directionRandomizer = directionRandomizer;
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
            var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
            var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
            var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
            direction.x += randX;
            direction.y += randY;
            direction.z += randZ;
            direction.normalize();
            BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
        };
        /**
         * Called by the particle System when the position is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param positionToUpdate is the position vector to update with the result
         * @param particle is the particle we are computed the position for
         */
        HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
            var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
            var v = BABYLON.Scalar.RandomRange(0, 1.0);
            var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
            var theta = Math.acos(2 * v - 1);
            var randX = randRadius * Math.cos(phi) * Math.sin(theta);
            var randY = randRadius * Math.cos(theta);
            var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        HemisphericParticleEmitter.prototype.clone = function () {
            var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setFloat("radius", this.radius);
            effect.setFloat("radiusRange", this.radiusRange);
            effect.setFloat("directionRandomizer", this.directionRandomizer);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        HemisphericParticleEmitter.prototype.getEffectDefines = function () {
            return "#define HEMISPHERICEMITTER";
        };
        /**
         * Returns the string "HemisphericParticleEmitter"
         * @returns a string containing the class name
         */
        HemisphericParticleEmitter.prototype.getClassName = function () {
            return "HemisphericParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        HemisphericParticleEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.getClassName();
            serializationObject.radius = this.radius;
            serializationObject.radiusRange = this.radiusRange;
            serializationObject.directionRandomizer = this.directionRandomizer;
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
            this.radius = serializationObject.radius;
            this.radiusRange = serializationObject.radiusRange;
            this.directionRandomizer = serializationObject.directionRandomizer;
        };
        return HemisphericParticleEmitter;
    }());
    BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Particle emitter emitting particles from a point.
     * It emits the particles randomly between 2 given directions.
     */
    var PointParticleEmitter = /** @class */ (function () {
        /**
         * Creates a new instance PointParticleEmitter
         */
        function PointParticleEmitter() {
            /**
             * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
             */
            this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
            /**
             * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
             */
            this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
        }
        /**
         * Called by the particle System when the direction is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param directionToUpdate is the direction vector to update with the result
         * @param particle is the particle we are computed the direction for
         */
        PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
            var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
            var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
            var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
            BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
        };
        /**
         * Called by the particle System when the position is computed for the created particle.
         * @param worldMatrix is the world matrix of the particle system
         * @param positionToUpdate is the position vector to update with the result
         * @param particle is the particle we are computed the position for
         */
        PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
        };
        /**
         * Clones the current emitter and returns a copy of it
         * @returns the new emitter
         */
        PointParticleEmitter.prototype.clone = function () {
            var newOne = new PointParticleEmitter();
            BABYLON.Tools.DeepCopy(this, newOne);
            return newOne;
        };
        /**
         * Called by the GPUParticleSystem to setup the update shader
         * @param effect defines the update shader
         */
        PointParticleEmitter.prototype.applyToShader = function (effect) {
            effect.setVector3("direction1", this.direction1);
            effect.setVector3("direction2", this.direction2);
        };
        /**
         * Returns a string to use to update the GPU particles update shader
         * @returns a string containng the defines string
         */
        PointParticleEmitter.prototype.getEffectDefines = function () {
            return "#define POINTEMITTER";
        };
        /**
         * Returns the string "PointParticleEmitter"
         * @returns a string containing the class name
         */
        PointParticleEmitter.prototype.getClassName = function () {
            return "PointParticleEmitter";
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        PointParticleEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.getClassName();
            serializationObject.direction1 = this.direction1.asArray();
            serializationObject.direction2 = this.direction2.asArray();
            return serializationObject;
        };
        /**
         * Parse properties from a JSON object
         * @param serializationObject defines the JSON object
         */
        PointParticleEmitter.prototype.parse = function (serializationObject) {
            BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
            BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
        };
        return PointParticleEmitter;
    }());
    BABYLON.PointParticleEmitter = PointParticleEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pointParticleEmitter.js.map

var BABYLON;
(function (BABYLON) {
    // Adds the parsers to the scene parsers.
    BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
        var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
        if (!individualParser) {
            return;
        }
        // Particles Systems
        if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
            for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
                var parsedParticleSystem = parsedData.particleSystems[index];
                container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
            }
        }
    });
    BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
        if (parsedParticleSystem.activeParticleCount) {
            var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
            return ps;
        }
        else {
            var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
            return ps;
        }
    });
    BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
        if (uniformsNames === void 0) { uniformsNames = []; }
        if (samplers === void 0) { samplers = []; }
        if (defines === void 0) { defines = ""; }
        var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
        var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
        if (defines.indexOf(" BILLBOARD") === -1) {
            defines += "\n#define BILLBOARD\n";
        }
        if (samplers.indexOf("diffuseSampler") === -1) {
            samplers.push("diffuseSampler");
        }
        return this.createEffect({
            vertex: "particles",
            fragmentElement: fragmentName
        }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
    };
    BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
        var results = new Array();
        for (var index = 0; index < this.getScene().particleSystems.length; index++) {
            var particleSystem = this.getScene().particleSystems[index];
            if (particleSystem.emitter === this) {
                results.push(particleSystem);
            }
        }
        return results;
    };
    BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
        var results = new Array();
        var descendants = this.getDescendants();
        descendants.push(this);
        for (var index = 0; index < this.getScene().particleSystems.length; index++) {
            var particleSystem = this.getScene().particleSystems[index];
            var emitter = particleSystem.emitter;
            if (emitter.position && descendants.indexOf(emitter) !== -1) {
                results.push(particleSystem);
            }
        }
        return results;
    };
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.particleSystemComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Type of sub emitter
     */
    var SubEmitterType;
    (function (SubEmitterType) {
        /**
         * Attached to the particle over it's lifetime
         */
        SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
        /**
         * Created when the particle dies
         */
        SubEmitterType[SubEmitterType["END"] = 1] = "END";
    })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
    /**
     * Sub emitter class used to emit particles from an existing particle
     */
    var SubEmitter = /** @class */ (function () {
        /**
         * Creates a sub emitter
         * @param particleSystem the particle system to be used by the sub emitter
         */
        function SubEmitter(
        /**
         * the particle system to be used by the sub emitter
         */
        particleSystem) {
            this.particleSystem = particleSystem;
            /**
             * Type of the submitter (Default: END)
             */
            this.type = SubEmitterType.END;
            /**
             * If the particle should inherit the direction from the particle it's attached to. (+Y will face the direction the particle is moving) (Default: false)
             * Note: This only is supported when using an emitter of type Mesh
             */
            this.inheritDirection = false;
            /**
             * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
             */
            this.inheritedVelocityAmount = 0;
            // Create mesh as emitter to support rotation
            if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
                particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
            }
            // Automatically dispose of subemitter when system is disposed
            particleSystem.onDisposeObservable.add(function () {
                if (particleSystem.emitter && particleSystem.emitter.dispose) {
                    particleSystem.emitter.dispose();
                }
            });
        }
        /**
         * Clones the sub emitter
         * @returns the cloned sub emitter
         */
        SubEmitter.prototype.clone = function () {
            // Clone particle system
            var emitter = this.particleSystem.emitter;
            if (!emitter) {
                emitter = new BABYLON.Vector3();
            }
            else if (emitter instanceof BABYLON.Vector3) {
                emitter = emitter.clone();
            }
            else if (emitter instanceof BABYLON.AbstractMesh) {
                emitter = new BABYLON.Mesh("", emitter.getScene());
                emitter.isVisible = false;
            }
            var clone = new SubEmitter(this.particleSystem.clone("", emitter));
            // Clone properties
            clone.type = this.type;
            clone.inheritDirection = this.inheritDirection;
            clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
            clone.particleSystem._disposeEmitterOnDispose = true;
            clone.particleSystem.disposeOnStop = true;
            return clone;
        };
        /**
         * Serialize current object to a JSON object
         * @returns the serialized object
         */
        SubEmitter.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.type = this.type;
            serializationObject.inheritDirection = this.inheritDirection;
            serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
            serializationObject.particleSystem = this.particleSystem.serialize();
            return serializationObject;
        };
        /**
         * Creates a new SubEmitter from a serialized JSON version
         * @param serializationObject defines the JSON object to read from
         * @param scene defines the hosting scene
         * @param rootUrl defines the rootUrl for data loading
         * @returns a new SubEmitter
         */
        SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
            var system = serializationObject.particleSystem;
            var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
            subEmitter.type = serializationObject.type;
            subEmitter.inheritDirection = serializationObject.inheritDirection;
            subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
            subEmitter.particleSystem._isSubEmitter = true;
            return subEmitter;
        };
        /** Release associated resources */
        SubEmitter.prototype.dispose = function () {
            this.particleSystem.dispose();
        };
        return SubEmitter;
    }());
    BABYLON.SubEmitter = SubEmitter;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.subEmitter.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
     *
     * This returned material effects how the mesh will look based on the code in the shaders.
     *
     * @see http://doc.babylonjs.com/how_to/shader_material
     */
    var ShaderMaterial = /** @class */ (function (_super) {
        __extends(ShaderMaterial, _super);
        /**
         * Instantiate a new shader material.
         * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh.
         * This returned material effects how the mesh will look based on the code in the shaders.
         * @see http://doc.babylonjs.com/how_to/shader_material
         * @param name Define the name of the material in the scene
         * @param scene Define the scene the material belongs to
         * @param shaderPath Defines  the route to the shader code in one of three ways:
         *     - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
         *     - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
         *     - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
         * @param options Define the options used to create the shader
         */
        function ShaderMaterial(name, scene, shaderPath, options) {
            if (options === void 0) { options = {}; }
            var _this = _super.call(this, name, scene) || this;
            _this._textures = {};
            _this._textureArrays = {};
            _this._floats = {};
            _this._ints = {};
            _this._floatsArrays = {};
            _this._colors3 = {};
            _this._colors3Arrays = {};
            _this._colors4 = {};
            _this._vectors2 = {};
            _this._vectors3 = {};
            _this._vectors4 = {};
            _this._matrices = {};
            _this._matrices3x3 = {};
            _this._matrices2x2 = {};
            _this._vectors2Arrays = {};
            _this._vectors3Arrays = {};
            _this._cachedWorldViewMatrix = new BABYLON.Matrix();
            _this._shaderPath = shaderPath;
            _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
            return _this;
        }
        /**
         * Gets the current class name of the material e.g. "ShaderMaterial"
         * Mainly use in serialization.
         * @returns the class name
         */
        ShaderMaterial.prototype.getClassName = function () {
            return "ShaderMaterial";
        };
        /**
         * Specifies if the material will require alpha blending
         * @returns a boolean specifying if alpha blending is needed
         */
        ShaderMaterial.prototype.needAlphaBlending = function () {
            return (this.alpha < 1.0) || this._options.needAlphaBlending;
        };
        /**
         * Specifies if this material should be rendered in alpha test mode
         * @returns a boolean specifying if an alpha test is needed.
         */
        ShaderMaterial.prototype.needAlphaTesting = function () {
            return this._options.needAlphaTesting;
        };
        ShaderMaterial.prototype._checkUniform = function (uniformName) {
            if (this._options.uniforms.indexOf(uniformName) === -1) {
                this._options.uniforms.push(uniformName);
            }
        };
        /**
         * Set a texture in the shader.
         * @param name Define the name of the uniform samplers as defined in the shader
         * @param texture Define the texture to bind to this sampler
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setTexture = function (name, texture) {
            if (this._options.samplers.indexOf(name) === -1) {
                this._options.samplers.push(name);
            }
            this._textures[name] = texture;
            return this;
        };
        /**
         * Set a texture array in the shader.
         * @param name Define the name of the uniform sampler array as defined in the shader
         * @param textures Define the list of textures to bind to this sampler
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setTextureArray = function (name, textures) {
            if (this._options.samplers.indexOf(name) === -1) {
                this._options.samplers.push(name);
            }
            this._checkUniform(name);
            this._textureArrays[name] = textures;
            return this;
        };
        /**
         * Set a float in the shader.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setFloat = function (name, value) {
            this._checkUniform(name);
            this._floats[name] = value;
            return this;
        };
        /**
         * Set a int in the shader.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setInt = function (name, value) {
            this._checkUniform(name);
            this._ints[name] = value;
            return this;
        };
        /**
         * Set an array of floats in the shader.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setFloats = function (name, value) {
            this._checkUniform(name);
            this._floatsArrays[name] = value;
            return this;
        };
        /**
         * Set a vec3 in the shader from a Color3.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setColor3 = function (name, value) {
            this._checkUniform(name);
            this._colors3[name] = value;
            return this;
        };
        /**
         * Set a vec3 array in the shader from a Color3 array.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setColor3Array = function (name, value) {
            this._checkUniform(name);
            this._colors3Arrays[name] = value.reduce(function (arr, color) {
                color.toArray(arr, arr.length);
                return arr;
            }, []);
            return this;
        };
        /**
         * Set a vec4 in the shader from a Color4.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setColor4 = function (name, value) {
            this._checkUniform(name);
            this._colors4[name] = value;
            return this;
        };
        /**
         * Set a vec2 in the shader from a Vector2.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setVector2 = function (name, value) {
            this._checkUniform(name);
            this._vectors2[name] = value;
            return this;
        };
        /**
         * Set a vec3 in the shader from a Vector3.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setVector3 = function (name, value) {
            this._checkUniform(name);
            this._vectors3[name] = value;
            return this;
        };
        /**
         * Set a vec4 in the shader from a Vector4.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setVector4 = function (name, value) {
            this._checkUniform(name);
            this._vectors4[name] = value;
            return this;
        };
        /**
         * Set a mat4 in the shader from a Matrix.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setMatrix = function (name, value) {
            this._checkUniform(name);
            this._matrices[name] = value;
            return this;
        };
        /**
         * Set a mat3 in the shader from a Float32Array.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
            this._checkUniform(name);
            this._matrices3x3[name] = value;
            return this;
        };
        /**
         * Set a mat2 in the shader from a Float32Array.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
            this._checkUniform(name);
            this._matrices2x2[name] = value;
            return this;
        };
        /**
         * Set a vec2 array in the shader from a number array.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setArray2 = function (name, value) {
            this._checkUniform(name);
            this._vectors2Arrays[name] = value;
            return this;
        };
        /**
         * Set a vec3 array in the shader from a number array.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the material itself allowing "fluent" like uniform updates
         */
        ShaderMaterial.prototype.setArray3 = function (name, value) {
            this._checkUniform(name);
            this._vectors3Arrays[name] = value;
            return this;
        };
        ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
            if (!mesh) {
                return true;
            }
            if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
                return false;
            }
            return false;
        };
        /**
         * Checks if the material is ready to render the requested mesh
         * @param mesh Define the mesh to render
         * @param useInstances Define whether or not the material is used with instances
         * @returns true if ready, otherwise false
         */
        ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
            var scene = this.getScene();
            var engine = scene.getEngine();
            if (!this.checkReadyOnEveryCall) {
                if (this._renderId === scene.getRenderId()) {
                    if (this._checkCache(scene, mesh, useInstances)) {
                        return true;
                    }
                }
            }
            // Instances
            var defines = [];
            var attribs = [];
            var fallbacks = new BABYLON.EffectFallbacks();
            for (var index = 0; index < this._options.defines.length; index++) {
                defines.push(this._options.defines[index]);
            }
            for (var index = 0; index < this._options.attributes.length; index++) {
                attribs.push(this._options.attributes[index]);
            }
            if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
                attribs.push(BABYLON.VertexBuffer.ColorKind);
                defines.push("#define VERTEXCOLOR");
            }
            if (useInstances) {
                defines.push("#define INSTANCES");
                BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
            }
            // Bones
            if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
                fallbacks.addCPUSkinningFallback(0, mesh);
                if (this._options.uniforms.indexOf("mBones") === -1) {
                    this._options.uniforms.push("mBones");
                }
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Textures
            for (var name in this._textures) {
                if (!this._textures[name].isReady()) {
                    return false;
                }
            }
            // Alpha test
            if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
                defines.push("#define ALPHATEST");
            }
            var previousEffect = this._effect;
            var join = defines.join("\n");
            this._effect = engine.createEffect(this._shaderPath, {
                attributes: attribs,
                uniformsNames: this._options.uniforms,
                uniformBuffersNames: this._options.uniformBuffers,
                samplers: this._options.samplers,
                defines: join,
                fallbacks: fallbacks,
                onCompiled: this.onCompiled,
                onError: this.onError
            }, engine);
            if (!this._effect.isReady()) {
                return false;
            }
            if (previousEffect !== this._effect) {
                scene.resetCachedMaterial();
            }
            this._renderId = scene.getRenderId();
            return true;
        };
        /**
         * Binds the world matrix to the material
         * @param world defines the world transformation matrix
         */
        ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
            var scene = this.getScene();
            if (!this._effect) {
                return;
            }
            if (this._options.uniforms.indexOf("world") !== -1) {
                this._effect.setMatrix("world", world);
            }
            if (this._options.uniforms.indexOf("worldView") !== -1) {
                world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
                this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
            }
            if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
                this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
            }
        };
        /**
         * Binds the material to the mesh
         * @param world defines the world transformation matrix
         * @param mesh defines the mesh to bind the material to
         */
        ShaderMaterial.prototype.bind = function (world, mesh) {
            // Std values
            this.bindOnlyWorldMatrix(world);
            if (this._effect && this.getScene().getCachedMaterial() !== this) {
                if (this._options.uniforms.indexOf("view") !== -1) {
                    this._effect.setMatrix("view", this.getScene().getViewMatrix());
                }
                if (this._options.uniforms.indexOf("projection") !== -1) {
                    this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
                }
                if (this._options.uniforms.indexOf("viewProjection") !== -1) {
                    this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
                }
                // Bones
                BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
                var name;
                // Texture
                for (name in this._textures) {
                    this._effect.setTexture(name, this._textures[name]);
                }
                // Texture arrays
                for (name in this._textureArrays) {
                    this._effect.setTextureArray(name, this._textureArrays[name]);
                }
                // Int
                for (name in this._ints) {
                    this._effect.setInt(name, this._ints[name]);
                }
                // Float
                for (name in this._floats) {
                    this._effect.setFloat(name, this._floats[name]);
                }
                // Floats
                for (name in this._floatsArrays) {
                    this._effect.setArray(name, this._floatsArrays[name]);
                }
                // Color3
                for (name in this._colors3) {
                    this._effect.setColor3(name, this._colors3[name]);
                }
                for (name in this._colors3Arrays) {
                    this._effect.setArray3(name, this._colors3Arrays[name]);
                }
                // Color4
                for (name in this._colors4) {
                    var color = this._colors4[name];
                    this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
                }
                // Vector2
                for (name in this._vectors2) {
                    this._effect.setVector2(name, this._vectors2[name]);
                }
                // Vector3
                for (name in this._vectors3) {
                    this._effect.setVector3(name, this._vectors3[name]);
                }
                // Vector4
                for (name in this._vectors4) {
                    this._effect.setVector4(name, this._vectors4[name]);
                }
                // Matrix
                for (name in this._matrices) {
                    this._effect.setMatrix(name, this._matrices[name]);
                }
                // Matrix 3x3
                for (name in this._matrices3x3) {
                    this._effect.setMatrix3x3(name, this._matrices3x3[name]);
                }
                // Matrix 2x2
                for (name in this._matrices2x2) {
                    this._effect.setMatrix2x2(name, this._matrices2x2[name]);
                }
                // Vector2Array
                for (name in this._vectors2Arrays) {
                    this._effect.setArray2(name, this._vectors2Arrays[name]);
                }
                // Vector3Array
                for (name in this._vectors3Arrays) {
                    this._effect.setArray3(name, this._vectors3Arrays[name]);
                }
            }
            this._afterBind(mesh);
        };
        /**
         * Gets the active textures from the material
         * @returns an array of textures
         */
        ShaderMaterial.prototype.getActiveTextures = function () {
            var activeTextures = _super.prototype.getActiveTextures.call(this);
            for (var name in this._textures) {
                activeTextures.push(this._textures[name]);
            }
            for (var name in this._textureArrays) {
                var array = this._textureArrays[name];
                for (var index = 0; index < array.length; index++) {
                    activeTextures.push(array[index]);
                }
            }
            return activeTextures;
        };
        /**
         * Specifies if the material uses a texture
         * @param texture defines the texture to check against the material
         * @returns a boolean specifying if the material uses the texture
         */
        ShaderMaterial.prototype.hasTexture = function (texture) {
            if (_super.prototype.hasTexture.call(this, texture)) {
                return true;
            }
            for (var name in this._textures) {
                if (this._textures[name] === texture) {
                    return true;
                }
            }
            for (var name in this._textureArrays) {
                var array = this._textureArrays[name];
                for (var index = 0; index < array.length; index++) {
                    if (array[index] === texture) {
                        return true;
                    }
                }
            }
            return false;
        };
        /**
         * Makes a duplicate of the material, and gives it a new name
         * @param name defines the new name for the duplicated material
         * @returns the cloned material
         */
        ShaderMaterial.prototype.clone = function (name) {
            var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
            return newShaderMaterial;
        };
        /**
         * Disposes the material
         * @param forceDisposeEffect specifies if effects should be forcefully disposed
         * @param forceDisposeTextures specifies if textures should be forcefully disposed
         */
        ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeTextures) {
                var name;
                for (name in this._textures) {
                    this._textures[name].dispose();
                }
                for (name in this._textureArrays) {
                    var array = this._textureArrays[name];
                    for (var index = 0; index < array.length; index++) {
                        array[index].dispose();
                    }
                }
            }
            this._textures = {};
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        /**
         * Serializes this material in a JSON representation
         * @returns the serialized material object
         */
        ShaderMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.ShaderMaterial";
            serializationObject.options = this._options;
            serializationObject.shaderPath = this._shaderPath;
            var name;
            // Texture
            serializationObject.textures = {};
            for (name in this._textures) {
                serializationObject.textures[name] = this._textures[name].serialize();
            }
            // Texture arrays
            serializationObject.textureArrays = {};
            for (name in this._textureArrays) {
                serializationObject.textureArrays[name] = [];
                var array = this._textureArrays[name];
                for (var index = 0; index < array.length; index++) {
                    serializationObject.textureArrays[name].push(array[index].serialize());
                }
            }
            // Float
            serializationObject.floats = {};
            for (name in this._floats) {
                serializationObject.floats[name] = this._floats[name];
            }
            // Float s
            serializationObject.FloatArrays = {};
            for (name in this._floatsArrays) {
                serializationObject.FloatArrays[name] = this._floatsArrays[name];
            }
            // Color3
            serializationObject.colors3 = {};
            for (name in this._colors3) {
                serializationObject.colors3[name] = this._colors3[name].asArray();
            }
            // Color3 array
            serializationObject.colors3Arrays = {};
            for (name in this._colors3Arrays) {
                serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
            }
            // Color4
            serializationObject.colors4 = {};
            for (name in this._colors4) {
                serializationObject.colors4[name] = this._colors4[name].asArray();
            }
            // Vector2
            serializationObject.vectors2 = {};
            for (name in this._vectors2) {
                serializationObject.vectors2[name] = this._vectors2[name].asArray();
            }
            // Vector3
            serializationObject.vectors3 = {};
            for (name in this._vectors3) {
                serializationObject.vectors3[name] = this._vectors3[name].asArray();
            }
            // Vector4
            serializationObject.vectors4 = {};
            for (name in this._vectors4) {
                serializationObject.vectors4[name] = this._vectors4[name].asArray();
            }
            // Matrix
            serializationObject.matrices = {};
            for (name in this._matrices) {
                serializationObject.matrices[name] = this._matrices[name].asArray();
            }
            // Matrix 3x3
            serializationObject.matrices3x3 = {};
            for (name in this._matrices3x3) {
                serializationObject.matrices3x3[name] = this._matrices3x3[name];
            }
            // Matrix 2x2
            serializationObject.matrices2x2 = {};
            for (name in this._matrices2x2) {
                serializationObject.matrices2x2[name] = this._matrices2x2[name];
            }
            // Vector2Array
            serializationObject.vectors2Arrays = {};
            for (name in this._vectors2Arrays) {
                serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
            }
            // Vector3Array
            serializationObject.vectors3Arrays = {};
            for (name in this._vectors3Arrays) {
                serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
            }
            return serializationObject;
        };
        /**
         * Creates a shader material from parsed shader material data
         * @param source defines the JSON represnetation of the material
         * @param scene defines the hosting scene
         * @param rootUrl defines the root URL to use to load textures and relative dependencies
         * @returns a new material
         */
        ShaderMaterial.Parse = function (source, scene, rootUrl) {
            var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
            var name;
            // Texture
            for (name in source.textures) {
                material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
            }
            // Texture arrays
            for (name in source.textureArrays) {
                var array = source.textureArrays[name];
                var textureArray = new Array();
                for (var index = 0; index < array.length; index++) {
                    textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
                }
                material.setTextureArray(name, textureArray);
            }
            // Float
            for (name in source.floats) {
                material.setFloat(name, source.floats[name]);
            }
            // Float s
            for (name in source.floatsArrays) {
                material.setFloats(name, source.floatsArrays[name]);
            }
            // Color3
            for (name in source.colors3) {
                material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
            }
            // Color3 arrays
            for (name in source.colors3Arrays) {
                var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
                    if (i % 3 === 0) {
                        arr.push([num]);
                    }
                    else {
                        arr[arr.length - 1].push(num);
                    }
                    return arr;
                }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
                material.setColor3Array(name, colors);
            }
            // Color4
            for (name in source.colors4) {
                material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
            }
            // Vector2
            for (name in source.vectors2) {
                material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
            }
            // Vector3
            for (name in source.vectors3) {
                material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
            }
            // Vector4
            for (name in source.vectors4) {
                material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
            }
            // Matrix
            for (name in source.matrices) {
                material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
            }
            // Matrix 3x3
            for (name in source.matrices3x3) {
                material.setMatrix3x3(name, source.matrices3x3[name]);
            }
            // Matrix 2x2
            for (name in source.matrices2x2) {
                material.setMatrix2x2(name, source.matrices2x2[name]);
            }
            // Vector2Array
            for (name in source.vectors2Arrays) {
                material.setArray2(name, source.vectors2Arrays[name]);
            }
            // Vector3Array
            for (name in source.vectors3Arrays) {
                material.setArray3(name, source.vectors3Arrays[name]);
            }
            return material;
        };
        return ShaderMaterial;
    }(BABYLON.Material));
    BABYLON.ShaderMaterial = ShaderMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.shaderMaterial.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Mesh representing the gorund
     */
    var GroundMesh = /** @class */ (function (_super) {
        __extends(GroundMesh, _super);
        function GroundMesh(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /** If octree should be generated */
            _this.generateOctree = false;
            return _this;
        }
        /**
         * "GroundMesh"
         * @returns "GroundMesh"
         */
        GroundMesh.prototype.getClassName = function () {
            return "GroundMesh";
        };
        Object.defineProperty(GroundMesh.prototype, "subdivisions", {
            /**
             * The minimum of x and y subdivisions
             */
            get: function () {
                return Math.min(this._subdivisionsX, this._subdivisionsY);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
            /**
             * X subdivisions
             */
            get: function () {
                return this._subdivisionsX;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
            /**
             * Y subdivisions
             */
            get: function () {
                return this._subdivisionsY;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
         * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
         * @param chunksCount the number of subdivisions for x and y
         * @param octreeBlocksSize (Default: 32)
         */
        GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
            if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
            this._subdivisionsX = chunksCount;
            this._subdivisionsY = chunksCount;
            this.subdivide(chunksCount);
            // Call the octree system optimization if it is defined.
            var thisAsAny = this;
            if (thisAsAny.createOrUpdateSubmeshesOctree) {
                thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
            }
        };
        /**
         * Returns a height (y) value in the Worl system :
         * the ground altitude at the coordinates (x, z) expressed in the World system.
         * @param x x coordinate
         * @param z z coordinate
         * @returns the ground y position if (x, z) are outside the ground surface.
         */
        GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
            var world = this.getWorldMatrix();
            var invMat = BABYLON.Tmp.Matrix[5];
            world.invertToRef(invMat);
            var tmpVect = BABYLON.Tmp.Vector3[8];
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
            x = tmpVect.x;
            z = tmpVect.z;
            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
                return this.position.y;
            }
            if (!this._heightQuads || this._heightQuads.length == 0) {
                this._initHeightQuads();
                this._computeHeightQuads();
            }
            var facet = this._getFacetAt(x, z);
            var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
            // return y in the World system
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
            return tmpVect.y;
        };
        /**
         * Returns a normalized vector (Vector3) orthogonal to the ground
         * at the ground coordinates (x, z) expressed in the World system.
         * @param x x coordinate
         * @param z z coordinate
         * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
         */
        GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
            var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
            this.getNormalAtCoordinatesToRef(x, z, normal);
            return normal;
        };
        /**
         * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
         * at the ground coordinates (x, z) expressed in the World system.
         * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
         * @param x x coordinate
         * @param z z coordinate
         * @param ref vector to store the result
         * @returns the GroundMesh.
         */
        GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
            var world = this.getWorldMatrix();
            var tmpMat = BABYLON.Tmp.Matrix[5];
            world.invertToRef(tmpMat);
            var tmpVect = BABYLON.Tmp.Vector3[8];
            BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
            x = tmpVect.x;
            z = tmpVect.z;
            if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
                return this;
            }
            if (!this._heightQuads || this._heightQuads.length == 0) {
                this._initHeightQuads();
                this._computeHeightQuads();
            }
            var facet = this._getFacetAt(x, z);
            BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
            return this;
        };
        /**
        * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
        * if the ground has been updated.
        * This can be used in the render loop.
        * @returns the GroundMesh.
        */
        GroundMesh.prototype.updateCoordinateHeights = function () {
            if (!this._heightQuads || this._heightQuads.length == 0) {
                this._initHeightQuads();
            }
            this._computeHeightQuads();
            return this;
        };
        // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
        GroundMesh.prototype._getFacetAt = function (x, z) {
            // retrieve col and row from x, z coordinates in the ground local system
            var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
            var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
            var quad = this._heightQuads[row * this._subdivisionsX + col];
            var facet;
            if (z < quad.slope.x * x + quad.slope.y) {
                facet = quad.facet1;
            }
            else {
                facet = quad.facet2;
            }
            return facet;
        };
        //  Creates and populates the heightMap array with "facet" elements :
        // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
        // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
        // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
        // facet2 :  Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
        // Returns the GroundMesh.
        GroundMesh.prototype._initHeightQuads = function () {
            var subdivisionsX = this._subdivisionsX;
            var subdivisionsY = this._subdivisionsY;
            this._heightQuads = new Array();
            for (var row = 0; row < subdivisionsY; row++) {
                for (var col = 0; col < subdivisionsX; col++) {
                    var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
                    this._heightQuads[row * subdivisionsX + col] = quad;
                }
            }
            return this;
        };
        // Compute each quad element values and update the the heightMap array :
        // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
        // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
        // facet2 :  Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
        // Returns the GroundMesh.
        GroundMesh.prototype._computeHeightQuads = function () {
            var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            if (!positions) {
                return this;
            }
            var v1 = BABYLON.Tmp.Vector3[3];
            var v2 = BABYLON.Tmp.Vector3[2];
            var v3 = BABYLON.Tmp.Vector3[1];
            var v4 = BABYLON.Tmp.Vector3[0];
            var v1v2 = BABYLON.Tmp.Vector3[4];
            var v1v3 = BABYLON.Tmp.Vector3[5];
            var v1v4 = BABYLON.Tmp.Vector3[6];
            var norm1 = BABYLON.Tmp.Vector3[7];
            var norm2 = BABYLON.Tmp.Vector3[8];
            var i = 0;
            var j = 0;
            var k = 0;
            var cd = 0; // 2D slope coefficient : z = cd * x + h
            var h = 0;
            var d1 = 0; // facet plane equation : ax + by + cz + d = 0
            var d2 = 0;
            var subdivisionsX = this._subdivisionsX;
            var subdivisionsY = this._subdivisionsY;
            for (var row = 0; row < subdivisionsY; row++) {
                for (var col = 0; col < subdivisionsX; col++) {
                    i = col * 3;
                    j = row * (subdivisionsX + 1) * 3;
                    k = (row + 1) * (subdivisionsX + 1) * 3;
                    v1.x = positions[j + i];
                    v1.y = positions[j + i + 1];
                    v1.z = positions[j + i + 2];
                    v2.x = positions[j + i + 3];
                    v2.y = positions[j + i + 4];
                    v2.z = positions[j + i + 5];
                    v3.x = positions[k + i];
                    v3.y = positions[k + i + 1];
                    v3.z = positions[k + i + 2];
                    v4.x = positions[k + i + 3];
                    v4.y = positions[k + i + 4];
                    v4.z = positions[k + i + 5];
                    // 2D slope V1V4
                    cd = (v4.z - v1.z) / (v4.x - v1.x);
                    h = v1.z - cd * v1.x; // v1 belongs to the slope
                    // facet equations :
                    // we compute each facet normal vector
                    // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
                    // we compute the value d by applying the equation to v1 which belongs to the plane
                    // then we store the facet equation in a Vector4
                    v2.subtractToRef(v1, v1v2);
                    v3.subtractToRef(v1, v1v3);
                    v4.subtractToRef(v1, v1v4);
                    BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
                    BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
                    norm1.normalize();
                    norm2.normalize();
                    d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
                    d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
                    var quad = this._heightQuads[row * subdivisionsX + col];
                    quad.slope.copyFromFloats(cd, h);
                    quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
                    quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
                }
            }
            return this;
        };
        /**
         * Serializes this ground mesh
         * @param serializationObject object to write serialization to
         */
        GroundMesh.prototype.serialize = function (serializationObject) {
            _super.prototype.serialize.call(this, serializationObject);
            serializationObject.subdivisionsX = this._subdivisionsX;
            serializationObject.subdivisionsY = this._subdivisionsY;
            serializationObject.minX = this._minX;
            serializationObject.maxX = this._maxX;
            serializationObject.minZ = this._minZ;
            serializationObject.maxZ = this._maxZ;
            serializationObject.width = this._width;
            serializationObject.height = this._height;
        };
        /**
         * Parses a serialized ground mesh
         * @param parsedMesh the serialized mesh
         * @param scene the scene to create the ground mesh in
         * @returns the created ground mesh
         */
        GroundMesh.Parse = function (parsedMesh, scene) {
            var result = new GroundMesh(parsedMesh.name, scene);
            result._subdivisionsX = parsedMesh.subdivisionsX || 1;
            result._subdivisionsY = parsedMesh.subdivisionsY || 1;
            result._minX = parsedMesh.minX;
            result._maxX = parsedMesh.maxX;
            result._minZ = parsedMesh.minZ;
            result._maxZ = parsedMesh.maxZ;
            result._width = parsedMesh.width;
            result._height = parsedMesh.height;
            return result;
        };
        return GroundMesh;
    }(BABYLON.Mesh));
    BABYLON.GroundMesh = GroundMesh;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.groundMesh.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Creates an instance based on a source mesh.
     */
    var InstancedMesh = /** @class */ (function (_super) {
        __extends(InstancedMesh, _super);
        function InstancedMesh(name, source) {
            var _this = _super.call(this, name, source.getScene()) || this;
            source.instances.push(_this);
            _this._sourceMesh = source;
            _this.position.copyFrom(source.position);
            _this.rotation.copyFrom(source.rotation);
            _this.scaling.copyFrom(source.scaling);
            if (source.rotationQuaternion) {
                _this.rotationQuaternion = source.rotationQuaternion.clone();
            }
            _this.infiniteDistance = source.infiniteDistance;
            _this.setPivotMatrix(source.getPivotMatrix());
            _this.refreshBoundingInfo();
            _this._syncSubMeshes();
            return _this;
        }
        /**
         * Returns the string "InstancedMesh".
         */
        InstancedMesh.prototype.getClassName = function () {
            return "InstancedMesh";
        };
        Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
            // Methods
            /**
             * If the source mesh receives shadows
             */
            get: function () {
                return this._sourceMesh.receiveShadows;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "material", {
            /**
             * The material of the source mesh
             */
            get: function () {
                return this._sourceMesh.material;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "visibility", {
            /**
             * Visibility of the source mesh
             */
            get: function () {
                return this._sourceMesh.visibility;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "skeleton", {
            /**
             * Skeleton of the source mesh
             */
            get: function () {
                return this._sourceMesh.skeleton;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
            /**
             * Rendering ground id of the source mesh
             */
            get: function () {
                return this._sourceMesh.renderingGroupId;
            },
            set: function (value) {
                if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
                    return;
                }
                //no-op with warning
                BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the total number of vertices (integer).
         */
        InstancedMesh.prototype.getTotalVertices = function () {
            return this._sourceMesh.getTotalVertices();
        };
        Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
            /**
             * The source mesh of the instance
             */
            get: function () {
                return this._sourceMesh;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Is this node ready to be used/rendered
         * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
         * @return {boolean} is it ready
         */
        InstancedMesh.prototype.isReady = function (completeCheck) {
            if (completeCheck === void 0) { completeCheck = false; }
            return this._sourceMesh.isReady(completeCheck, true);
        };
        /**
         * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
         * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
         * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
         * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
         */
        InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
            return this._sourceMesh.getVerticesData(kind, copyWhenShared);
        };
        /**
         * Sets the vertex data of the mesh geometry for the requested `kind`.
         * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
         * The `data` are either a numeric array either a Float32Array.
         * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
         * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
         * Note that a new underlying VertexBuffer object is created each call.
         * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
         *
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         *
         * Returns the Mesh.
         */
        InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
            if (this.sourceMesh) {
                this.sourceMesh.setVerticesData(kind, data, updatable, stride);
            }
            return this.sourceMesh;
        };
        /**
         * Updates the existing vertex data of the mesh geometry for the requested `kind`.
         * If the mesh has no geometry, it is simply returned as it is.
         * The `data` are either a numeric array either a Float32Array.
         * No new underlying VertexBuffer object is created.
         * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
         * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
         *
         * Possible `kind` values :
         * - BABYLON.VertexBuffer.PositionKind
         * - BABYLON.VertexBuffer.UVKind
         * - BABYLON.VertexBuffer.UV2Kind
         * - BABYLON.VertexBuffer.UV3Kind
         * - BABYLON.VertexBuffer.UV4Kind
         * - BABYLON.VertexBuffer.UV5Kind
         * - BABYLON.VertexBuffer.UV6Kind
         * - BABYLON.VertexBuffer.ColorKind
         * - BABYLON.VertexBuffer.MatricesIndicesKind
         * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
         * - BABYLON.VertexBuffer.MatricesWeightsKind
         * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
         *
         * Returns the Mesh.
         */
        InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
            if (this.sourceMesh) {
                this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
            }
            return this.sourceMesh;
        };
        /**
         * Sets the mesh indices.
         * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
         * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
         * This method creates a new index buffer each call.
         * Returns the Mesh.
         */
        InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
            if (totalVertices === void 0) { totalVertices = null; }
            if (this.sourceMesh) {
                this.sourceMesh.setIndices(indices, totalVertices);
            }
            return this.sourceMesh;
        };
        /**
         * Boolean : True if the mesh owns the requested kind of data.
         */
        InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
            return this._sourceMesh.isVerticesDataPresent(kind);
        };
        /**
         * Returns an array of indices (IndicesArray).
         */
        InstancedMesh.prototype.getIndices = function () {
            return this._sourceMesh.getIndices();
        };
        Object.defineProperty(InstancedMesh.prototype, "_positions", {
            get: function () {
                return this._sourceMesh._positions;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Sets a new updated BoundingInfo to the mesh.
         * @returns the mesh.
         */
        InstancedMesh.prototype.refreshBoundingInfo = function () {
            var meshBB = this._sourceMesh.getBoundingInfo();
            this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
            this._updateBoundingInfo();
            return this;
        };
        /** @hidden */
        InstancedMesh.prototype._preActivate = function () {
            if (this._currentLOD) {
                this._currentLOD._preActivate();
            }
            return this;
        };
        /** @hidden */
        InstancedMesh.prototype._activate = function (renderId) {
            if (this._currentLOD) {
                this._currentLOD._registerInstanceForRenderId(this, renderId);
            }
            return this;
        };
        /**
         * Returns the current associated LOD AbstractMesh.
         */
        InstancedMesh.prototype.getLOD = function (camera) {
            if (!camera) {
                return this;
            }
            var boundingInfo = this.getBoundingInfo();
            this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
            if (this._currentLOD === this.sourceMesh) {
                return this;
            }
            return this._currentLOD;
        };
        /** @hidden */
        InstancedMesh.prototype._syncSubMeshes = function () {
            this.releaseSubMeshes();
            if (this._sourceMesh.subMeshes) {
                for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
                    this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
                }
            }
            return this;
        };
        /** @hidden */
        InstancedMesh.prototype._generatePointsArray = function () {
            return this._sourceMesh._generatePointsArray();
        };
        /**
         * Creates a new InstancedMesh from the current mesh.
         * - name (string) : the cloned mesh name
         * - newParent (optional Node) : the optional Node to parent the clone to.
         * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
         *
         * Returns the clone.
         */
        InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
            var result = this._sourceMesh.createInstance(name);
            // Deep copy
            BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
            // Bounding info
            this.refreshBoundingInfo();
            // Parent
            if (newParent) {
                result.parent = newParent;
            }
            if (!doNotCloneChildren) {
                // Children
                for (var index = 0; index < this.getScene().meshes.length; index++) {
                    var mesh = this.getScene().meshes[index];
                    if (mesh.parent === this) {
                        mesh.clone(mesh.name, result);
                    }
                }
            }
            result.computeWorldMatrix(true);
            return result;
        };
        /**
         * Disposes the InstancedMesh.
         * Returns nothing.
         */
        InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            // Remove from mesh
            var index = this._sourceMesh.instances.indexOf(this);
            this._sourceMesh.instances.splice(index, 1);
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        return InstancedMesh;
    }(BABYLON.AbstractMesh));
    BABYLON.InstancedMesh = InstancedMesh;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.instancedMesh.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Line mesh
     * @see https://doc.babylonjs.com/babylon101/parametric_shapes
     */
    var LinesMesh = /** @class */ (function (_super) {
        __extends(LinesMesh, _super);
        /**
         * Creates a new LinesMesh
         * @param name defines the name
         * @param scene defines the hosting scene
         * @param parent defines the parent mesh if any
         * @param source defines the optional source LinesMesh used to clone data from
         * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
         * When false, achieved by calling a clone(), also passing False.
         * This will make creation of children, recursive.
         * @param useVertexColor defines if this LinesMesh supports vertex color
         * @param useVertexAlpha defines if this LinesMesh supports vertex alpha
         */
        function LinesMesh(name, scene, parent, source, doNotCloneChildren, 
        /**
         * If vertex color should be applied to the mesh
         */
        useVertexColor, 
        /**
         * If vertex alpha should be applied to the mesh
         */
        useVertexAlpha) {
            if (scene === void 0) { scene = null; }
            if (parent === void 0) { parent = null; }
            var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
            _this.useVertexColor = useVertexColor;
            _this.useVertexAlpha = useVertexAlpha;
            /**
             * Color of the line (Default: White)
             */
            _this.color = new BABYLON.Color3(1, 1, 1);
            /**
             * Alpha of the line (Default: 1)
             */
            _this.alpha = 1;
            if (source) {
                _this.color = source.color.clone();
                _this.alpha = source.alpha;
                _this.useVertexColor = source.useVertexColor;
                _this.useVertexAlpha = source.useVertexAlpha;
            }
            _this._intersectionThreshold = 0.1;
            var defines = [];
            var options = {
                attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
                uniforms: ["world", "viewProjection"],
                needAlphaBlending: true,
                defines: defines
            };
            if (useVertexAlpha === false) {
                options.needAlphaBlending = false;
            }
            if (!useVertexColor) {
                options.uniforms.push("color");
            }
            else {
                options.defines.push("#define VERTEXCOLOR");
                options.attributes.push(BABYLON.VertexBuffer.ColorKind);
            }
            _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
            return _this;
        }
        Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
            /**
             * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
             * This margin is expressed in world space coordinates, so its value may vary.
             * Default value is 0.1
             * @returns the intersection Threshold value.
             */
            get: function () {
                return this._intersectionThreshold;
            },
            /**
             * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
             * This margin is expressed in world space coordinates, so its value may vary.
             */
            set: function (value) {
                if (this._intersectionThreshold === value) {
                    return;
                }
                this._intersectionThreshold = value;
                if (this.geometry) {
                    this.geometry.boundingBias = new BABYLON.Vector2(0, value);
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "LineMesh"
         */
        LinesMesh.prototype.getClassName = function () {
            return "LinesMesh";
        };
        Object.defineProperty(LinesMesh.prototype, "material", {
            /**
             * @hidden
             */
            get: function () {
                return this._colorShader;
            },
            /**
             * @hidden
             */
            set: function (value) {
                // Do nothing
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
            /**
             * @hidden
             */
            get: function () {
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
            if (!this._geometry) {
                return this;
            }
            // VBOs
            this._geometry._bind(this._colorShader.getEffect());
            // Color
            if (!this.useVertexColor) {
                this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
            }
            return this;
        };
        /** @hidden */
        LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
            if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
                return this;
            }
            var engine = this.getScene().getEngine();
            // Draw order
            engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
            return this;
        };
        /**
         * Disposes of the line mesh
         * @param doNotRecurse If children should be disposed
         */
        LinesMesh.prototype.dispose = function (doNotRecurse) {
            this._colorShader.dispose();
            _super.prototype.dispose.call(this, doNotRecurse);
        };
        /**
         * Returns a new LineMesh object cloned from the current one.
         */
        LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
            return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
        };
        return LinesMesh;
    }(BABYLON.Mesh));
    BABYLON.LinesMesh = LinesMesh;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.linesMesh.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class implement a typical dictionary using a string as key and the generic type T as value.
     * The underlying implementation relies on an associative array to ensure the best performances.
     * The value can be anything including 'null' but except 'undefined'
     */
    var StringDictionary = /** @class */ (function () {
        function StringDictionary() {
            this._count = 0;
            this._data = {};
        }
        /**
         * This will clear this dictionary and copy the content from the 'source' one.
         * If the T value is a custom object, it won't be copied/cloned, the same object will be used
         * @param source the dictionary to take the content from and copy to this dictionary
         */
        StringDictionary.prototype.copyFrom = function (source) {
            var _this = this;
            this.clear();
            source.forEach(function (t, v) { return _this.add(t, v); });
        };
        /**
         * Get a value based from its key
         * @param key the given key to get the matching value from
         * @return the value if found, otherwise undefined is returned
         */
        StringDictionary.prototype.get = function (key) {
            var val = this._data[key];
            if (val !== undefined) {
                return val;
            }
            return undefined;
        };
        /**
         * Get a value from its key or add it if it doesn't exist.
         * This method will ensure you that a given key/data will be present in the dictionary.
         * @param key the given key to get the matching value from
         * @param factory the factory that will create the value if the key is not present in the dictionary.
         * The factory will only be invoked if there's no data for the given key.
         * @return the value corresponding to the key.
         */
        StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
            var val = this.get(key);
            if (val !== undefined) {
                return val;
            }
            val = factory(key);
            if (val) {
                this.add(key, val);
            }
            return val;
        };
        /**
         * Get a value from its key if present in the dictionary otherwise add it
         * @param key the key to get the value from
         * @param val if there's no such key/value pair in the dictionary add it with this value
         * @return the value corresponding to the key
         */
        StringDictionary.prototype.getOrAdd = function (key, val) {
            var curVal = this.get(key);
            if (curVal !== undefined) {
                return curVal;
            }
            this.add(key, val);
            return val;
        };
        /**
         * Check if there's a given key in the dictionary
         * @param key the key to check for
         * @return true if the key is present, false otherwise
         */
        StringDictionary.prototype.contains = function (key) {
            return this._data[key] !== undefined;
        };
        /**
         * Add a new key and its corresponding value
         * @param key the key to add
         * @param value the value corresponding to the key
         * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
         */
        StringDictionary.prototype.add = function (key, value) {
            if (this._data[key] !== undefined) {
                return false;
            }
            this._data[key] = value;
            ++this._count;
            return true;
        };
        /**
         * Update a specific value associated to a key
         * @param key defines the key to use
         * @param value defines the value to store
         * @returns true if the value was updated (or false if the key was not found)
         */
        StringDictionary.prototype.set = function (key, value) {
            if (this._data[key] === undefined) {
                return false;
            }
            this._data[key] = value;
            return true;
        };
        /**
         * Get the element of the given key and remove it from the dictionary
         * @param key defines the key to search
         * @returns the value associated with the key or null if not found
         */
        StringDictionary.prototype.getAndRemove = function (key) {
            var val = this.get(key);
            if (val !== undefined) {
                delete this._data[key];
                --this._count;
                return val;
            }
            return null;
        };
        /**
         * Remove a key/value from the dictionary.
         * @param key the key to remove
         * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
         */
        StringDictionary.prototype.remove = function (key) {
            if (this.contains(key)) {
                delete this._data[key];
                --this._count;
                return true;
            }
            return false;
        };
        /**
         * Clear the whole content of the dictionary
         */
        StringDictionary.prototype.clear = function () {
            this._data = {};
            this._count = 0;
        };
        Object.defineProperty(StringDictionary.prototype, "count", {
            /**
             * Gets the current count
             */
            get: function () {
                return this._count;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Execute a callback on each key/val of the dictionary.
         * Note that you can remove any element in this dictionary in the callback implementation
         * @param callback the callback to execute on a given key/value pair
         */
        StringDictionary.prototype.forEach = function (callback) {
            for (var cur in this._data) {
                var val = this._data[cur];
                callback(cur, val);
            }
        };
        /**
         * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
         * If the callback returns null or undefined the method will iterate to the next key/value pair
         * Note that you can remove any element in this dictionary in the callback implementation
         * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
         * @returns the first item
         */
        StringDictionary.prototype.first = function (callback) {
            for (var cur in this._data) {
                var val = this._data[cur];
                var res = callback(cur, val);
                if (res) {
                    return res;
                }
            }
            return null;
        };
        return StringDictionary;
    }());
    BABYLON.StringDictionary = StringDictionary;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stringDictionary.js.map

var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        /**
         * Class used to render a debug view of a given skeleton
         * @see http://www.babylonjs-playground.com/#1BZJVJ#8
         */
        var SkeletonViewer = /** @class */ (function () {
            /**
             * Creates a new SkeletonViewer
             * @param skeleton defines the skeleton to render
             * @param mesh defines the mesh attached to the skeleton
             * @param scene defines the hosting scene
             * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
             * @param renderingGroupId defines the rendering group id to use with the viewer
             */
            function SkeletonViewer(
            /** defines the skeleton to render */
            skeleton, 
            /** defines the mesh attached to the skeleton */
            mesh, scene, 
            /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)  */
            autoUpdateBonesMatrices, 
            /** defines the rendering group id to use with the viewer */
            renderingGroupId) {
                if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
                if (renderingGroupId === void 0) { renderingGroupId = 1; }
                this.skeleton = skeleton;
                this.mesh = mesh;
                this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
                this.renderingGroupId = renderingGroupId;
                /** Gets or sets the color used to render the skeleton */
                this.color = BABYLON.Color3.White();
                this._debugLines = new Array();
                this._isEnabled = false;
                this._scene = scene;
                this.update();
                this._renderFunction = this.update.bind(this);
            }
            Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
                get: function () {
                    return this._isEnabled;
                },
                /** Gets or sets a boolean indicating if the viewer is enabled */
                set: function (value) {
                    if (this._isEnabled === value) {
                        return;
                    }
                    this._isEnabled = value;
                    if (value) {
                        this._scene.registerBeforeRender(this._renderFunction);
                    }
                    else {
                        this._scene.unregisterBeforeRender(this._renderFunction);
                    }
                },
                enumerable: true,
                configurable: true
            });
            SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
                if (x === void 0) { x = 0; }
                if (y === void 0) { y = 0; }
                if (z === void 0) { z = 0; }
                var tmat = BABYLON.Tmp.Matrix[0];
                var parentBone = bone.getParent();
                tmat.copyFrom(bone.getLocalMatrix());
                if (x !== 0 || y !== 0 || z !== 0) {
                    var tmat2 = BABYLON.Tmp.Matrix[1];
                    BABYLON.Matrix.IdentityToRef(tmat2);
                    tmat2.m[12] = x;
                    tmat2.m[13] = y;
                    tmat2.m[14] = z;
                    tmat2.multiplyToRef(tmat, tmat);
                }
                if (parentBone) {
                    tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
                }
                tmat.multiplyToRef(meshMat, tmat);
                position.x = tmat.m[12];
                position.y = tmat.m[13];
                position.z = tmat.m[14];
            };
            SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
                var len = bones.length;
                var meshPos = this.mesh.position;
                for (var i = 0; i < len; i++) {
                    var bone = bones[i];
                    var points = this._debugLines[i];
                    if (!points) {
                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                        this._debugLines[i] = points;
                    }
                    this._getBonePosition(points[0], bone, meshMat);
                    this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
                    points[0].subtractInPlace(meshPos);
                    points[1].subtractInPlace(meshPos);
                }
            };
            SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
                var len = bones.length;
                var boneNum = 0;
                var meshPos = this.mesh.position;
                for (var i = len - 1; i >= 0; i--) {
                    var childBone = bones[i];
                    var parentBone = childBone.getParent();
                    if (!parentBone) {
                        continue;
                    }
                    var points = this._debugLines[boneNum];
                    if (!points) {
                        points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                        this._debugLines[boneNum] = points;
                    }
                    childBone.getAbsolutePositionToRef(this.mesh, points[0]);
                    parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
                    points[0].subtractInPlace(meshPos);
                    points[1].subtractInPlace(meshPos);
                    boneNum++;
                }
            };
            /** Update the viewer to sync with current skeleton state */
            SkeletonViewer.prototype.update = function () {
                if (this.autoUpdateBonesMatrices) {
                    this.skeleton.computeAbsoluteTransforms();
                }
                if (this.skeleton.bones[0].length === undefined) {
                    this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
                }
                else {
                    this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
                }
                if (!this._debugMesh) {
                    this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
                    this._debugMesh.renderingGroupId = this.renderingGroupId;
                }
                else {
                    BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
                }
                this._debugMesh.position.copyFrom(this.mesh.position);
                this._debugMesh.color = this.color;
            };
            /** Release associated resources */
            SkeletonViewer.prototype.dispose = function () {
                if (this._debugMesh) {
                    this.isEnabled = false;
                    this._debugMesh.dispose();
                    this._debugMesh = null;
                }
            };
            return SkeletonViewer;
        }());
        Debug.SkeletonViewer = SkeletonViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.skeletonViewer.js.map

/**
 * Module Debug contains the (visual) components to debug a scene correctly
 */
var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        /**
         * The Axes viewer will show 3 axes in a specific point in space
         */
        var AxesViewer = /** @class */ (function () {
            /**
             * Creates a new AxesViewer
             * @param scene defines the hosting scene
             * @param scaleLines defines a number used to scale line length (1 by default)
             */
            function AxesViewer(scene, scaleLines) {
                if (scaleLines === void 0) { scaleLines = 1; }
                this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
                /**
                 * Gets or sets a number used to scale line length
                 */
                this.scaleLines = 1;
                this.scaleLines = scaleLines;
                this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
                this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
                this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
                this._xmesh.renderingGroupId = 2;
                this._ymesh.renderingGroupId = 2;
                this._zmesh.renderingGroupId = 2;
                this._xmesh.material.checkReadyOnlyOnce = true;
                this._xmesh.color = new BABYLON.Color3(1, 0, 0);
                this._ymesh.material.checkReadyOnlyOnce = true;
                this._ymesh.color = new BABYLON.Color3(0, 1, 0);
                this._zmesh.material.checkReadyOnlyOnce = true;
                this._zmesh.color = new BABYLON.Color3(0, 0, 1);
                this.scene = scene;
            }
            /**
             * Force the viewer to update
             * @param position defines the position of the viewer
             * @param xaxis defines the x axis of the viewer
             * @param yaxis defines the y axis of the viewer
             * @param zaxis defines the z axis of the viewer
             */
            AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
                var scaleLines = this.scaleLines;
                if (this._xmesh) {
                    this._xmesh.position.copyFrom(position);
                }
                if (this._ymesh) {
                    this._ymesh.position.copyFrom(position);
                }
                if (this._zmesh) {
                    this._zmesh.position.copyFrom(position);
                }
                var point2 = this._xline[1];
                point2.x = xaxis.x * scaleLines;
                point2.y = xaxis.y * scaleLines;
                point2.z = xaxis.z * scaleLines;
                BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
                point2 = this._yline[1];
                point2.x = yaxis.x * scaleLines;
                point2.y = yaxis.y * scaleLines;
                point2.z = yaxis.z * scaleLines;
                BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
                point2 = this._zline[1];
                point2.x = zaxis.x * scaleLines;
                point2.y = zaxis.y * scaleLines;
                point2.z = zaxis.z * scaleLines;
                BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
            };
            /** Releases resources */
            AxesViewer.prototype.dispose = function () {
                if (this._xmesh) {
                    this._xmesh.dispose();
                }
                if (this._ymesh) {
                    this._ymesh.dispose();
                }
                if (this._zmesh) {
                    this._zmesh.dispose();
                }
                this._xmesh = null;
                this._ymesh = null;
                this._zmesh = null;
                this.scene = null;
            };
            return AxesViewer;
        }());
        Debug.AxesViewer = AxesViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.axesViewer.js.map


var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        /**
         * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
         * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
         */
        var BoneAxesViewer = /** @class */ (function (_super) {
            __extends(BoneAxesViewer, _super);
            /**
             * Creates a new BoneAxesViewer
             * @param scene defines the hosting scene
             * @param bone defines the target bone
             * @param mesh defines the target mesh
             * @param scaleLines defines a scaling factor for line length (1 by default)
             */
            function BoneAxesViewer(scene, bone, mesh, scaleLines) {
                if (scaleLines === void 0) { scaleLines = 1; }
                var _this = _super.call(this, scene, scaleLines) || this;
                /** Gets current position */
                _this.pos = BABYLON.Vector3.Zero();
                /** Gets direction of X axis */
                _this.xaxis = BABYLON.Vector3.Zero();
                /** Gets direction of Y axis */
                _this.yaxis = BABYLON.Vector3.Zero();
                /** Gets direction of Z axis */
                _this.zaxis = BABYLON.Vector3.Zero();
                _this.mesh = mesh;
                _this.bone = bone;
                return _this;
            }
            /**
             * Force the viewer to update
             */
            BoneAxesViewer.prototype.update = function () {
                if (!this.mesh || !this.bone) {
                    return;
                }
                var bone = this.bone;
                bone.getAbsolutePositionToRef(this.mesh, this.pos);
                bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
                bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
                bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
                _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
            };
            /** Releases resources */
            BoneAxesViewer.prototype.dispose = function () {
                if (this.mesh) {
                    this.mesh = null;
                    this.bone = null;
                    _super.prototype.dispose.call(this);
                }
            };
            return BoneAxesViewer;
        }(Debug.AxesViewer));
        Debug.BoneAxesViewer = BoneAxesViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boneAxesViewer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * As raycast might be hard to debug, the RayHelper can help rendering the different rays
     * in order to better appreciate the issue one might have.
     * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
     */
    var RayHelper = /** @class */ (function () {
        /**
         * Instantiate a new ray helper.
         * As raycast might be hard to debug, the RayHelper can help rendering the different rays
         * in order to better appreciate the issue one might have.
         * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
         * @param ray Defines the ray we are currently tryin to visualize
         */
        function RayHelper(ray) {
            this.ray = ray;
        }
        /**
         * Helper function to create a colored helper in a scene in one line.
         * @param ray Defines the ray we are currently tryin to visualize
         * @param scene Defines the scene the ray is used in
         * @param color Defines the color we want to see the ray in
         * @returns The newly created ray helper.
         */
        RayHelper.CreateAndShow = function (ray, scene, color) {
            var helper = new RayHelper(ray);
            helper.show(scene, color);
            return helper;
        };
        /**
         * Shows the ray we are willing to debug.
         * @param scene Defines the scene the ray needs to be rendered in
         * @param color Defines the color the ray needs to be rendered in
         */
        RayHelper.prototype.show = function (scene, color) {
            if (!this._renderFunction && this.ray) {
                var ray = this.ray;
                this._renderFunction = this._render.bind(this);
                this._scene = scene;
                this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
                this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
                if (this._renderFunction) {
                    this._scene.registerBeforeRender(this._renderFunction);
                }
            }
            if (color && this._renderLine) {
                this._renderLine.color.copyFrom(color);
            }
        };
        /**
         * Hides the ray we are debugging.
         */
        RayHelper.prototype.hide = function () {
            if (this._renderFunction && this._scene) {
                this._scene.unregisterBeforeRender(this._renderFunction);
                this._scene = null;
                this._renderFunction = null;
                if (this._renderLine) {
                    this._renderLine.dispose();
                    this._renderLine = null;
                }
                this._renderPoints = [];
            }
        };
        RayHelper.prototype._render = function () {
            var ray = this.ray;
            if (!ray) {
                return;
            }
            var point = this._renderPoints[1];
            var len = Math.min(ray.length, 1000000);
            point.copyFrom(ray.direction);
            point.scaleInPlace(len);
            point.addInPlace(ray.origin);
            BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
        };
        /**
         * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
         * @param mesh Defines the mesh we want the helper attached to
         * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
         * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
         * @param length Defines the length of the ray
         */
        RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
            this._attachedToMesh = mesh;
            var ray = this.ray;
            if (!ray) {
                return;
            }
            if (!ray.direction) {
                ray.direction = BABYLON.Vector3.Zero();
            }
            if (!ray.origin) {
                ray.origin = BABYLON.Vector3.Zero();
            }
            if (length) {
                ray.length = length;
            }
            if (!meshSpaceOrigin) {
                meshSpaceOrigin = BABYLON.Vector3.Zero();
            }
            if (!meshSpaceDirection) {
                // -1 so that this will work with Mesh.lookAt
                meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
            }
            if (!this._meshSpaceDirection) {
                this._meshSpaceDirection = meshSpaceDirection.clone();
                this._meshSpaceOrigin = meshSpaceOrigin.clone();
            }
            else {
                this._meshSpaceDirection.copyFrom(meshSpaceDirection);
                this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
            }
            if (!this._updateToMeshFunction) {
                this._updateToMeshFunction = this._updateToMesh.bind(this);
                this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
            }
            this._updateToMesh();
        };
        /**
         * Detach the ray helper from the mesh it has previously been attached to.
         */
        RayHelper.prototype.detachFromMesh = function () {
            if (this._attachedToMesh) {
                if (this._updateToMeshFunction) {
                    this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
                }
                this._attachedToMesh = null;
                this._updateToMeshFunction = null;
            }
        };
        RayHelper.prototype._updateToMesh = function () {
            var ray = this.ray;
            if (!this._attachedToMesh || !ray) {
                return;
            }
            if (this._attachedToMesh._isDisposed) {
                this.detachFromMesh();
                return;
            }
            this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
            BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
        };
        /**
         * Dispose the helper and release its associated resources.
         */
        RayHelper.prototype.dispose = function () {
            this.hide();
            this.detachFromMesh();
            this.ray = null;
        };
        return RayHelper;
    }());
    BABYLON.RayHelper = RayHelper;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.rayHelper.js.map

var BABYLON;
(function (BABYLON) {
    Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
        get: function () {
            if (!this._debugLayer) {
                this._debugLayer = new DebugLayer(this);
            }
            return this._debugLayer;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * The debug layer (aka Inspector) is the go to tool in order to better understand
     * what is happening in your scene
     * @see http://doc.babylonjs.com/features/playground_debuglayer
     */
    var DebugLayer = /** @class */ (function () {
        /**
         * Instantiates a new debug layer.
         * The debug layer (aka Inspector) is the go to tool in order to better understand
         * what is happening in your scene
         * @see http://doc.babylonjs.com/features/playground_debuglayer
         * @param scene Defines the scene to inspect
         */
        function DebugLayer(scene) {
            var _this = this;
            this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
            /**
             * Observable triggered when a property is changed through the inspector.
             */
            this.onPropertyChangedObservable = new BABYLON.Observable();
            this._scene = scene;
            this._scene.onDisposeObservable.add(function () {
                // Debug layer
                if (_this._scene._debugLayer) {
                    _this._scene._debugLayer.hide();
                }
            });
        }
        /** Creates the inspector window. */
        DebugLayer.prototype._createInspector = function (config) {
            if (config === void 0) { config = {}; }
            var popup = config.popup || false;
            var initialTab = config.initialTab || 0;
            var parentElement = config.parentElement || null;
            if (!this._inspector) {
                this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
                this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
            } // else nothing to do as instance is already created
        };
        /**
         * Get if the inspector is visible or not.
         * @returns true if visible otherwise, false
         */
        DebugLayer.prototype.isVisible = function () {
            if (!this._inspector) {
                return false;
            }
            return true;
        };
        /**
         * Hide the inspector and close its window.
         */
        DebugLayer.prototype.hide = function () {
            if (this._inspector) {
                try {
                    this._inspector.dispose();
                }
                catch (e) {
                    // If the inspector has been removed directly from the inspector tool
                }
                this.onPropertyChangedObservable.clear();
                this._inspector = null;
            }
        };
        /**
        *
        * Launch the debugLayer.
        *
        * initialTab:
        * | Value | Tab Name |
        * | --- | --- |
        * | 0 | Scene |
        * | 1 | Console |
        * | 2 | Stats |
        * | 3 | Textures |
        * | 4 | Mesh |
        * | 5 | Light |
        * | 6 | Material |
        * | 7 | GLTF |
        * | 8 | GUI |
        * | 9 | Physics |
        * | 10 | Camera |
        * | 11 | Audio |
        *
        * @param config Define the configuration of the inspector
        */
        DebugLayer.prototype.show = function (config) {
            if (config === void 0) { config = {}; }
            if (typeof this.BJSINSPECTOR == 'undefined') {
                // Load inspector and add it to the DOM
                BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
            }
            else {
                // Otherwise creates the inspector
                this._createInspector(config);
            }
        };
        /**
         * Gets the active tab
         * @return the index of the active tab or -1 if the inspector is hidden
         */
        DebugLayer.prototype.getActiveTab = function () {
            return this._inspector ? this._inspector.getActiveTabIndex() : -1;
        };
        /**
         * Define the url to get the inspector script from.
         * By default it uses the babylonjs CDN.
         * @ignoreNaming
         */
        DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
        return DebugLayer;
    }());
    BABYLON.DebugLayer = DebugLayer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.debugLayer.js.map

var BABYLON;
(function (BABYLON) {
    var Debug;
    (function (Debug) {
        /**
         * Used to show the physics impostor around the specific mesh
         */
        var PhysicsViewer = /** @class */ (function () {
            /**
             * Creates a new PhysicsViewer
             * @param scene defines the hosting scene
             */
            function PhysicsViewer(scene) {
                /** @hidden */
                this._impostors = [];
                /** @hidden */
                this._meshes = [];
                /** @hidden */
                this._numMeshes = 0;
                this._scene = scene || BABYLON.Engine.LastCreatedScene;
                var physicEngine = this._scene.getPhysicsEngine();
                if (physicEngine) {
                    this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
                }
            }
            /** @hidden */
            PhysicsViewer.prototype._updateDebugMeshes = function () {
                var plugin = this._physicsEnginePlugin;
                for (var i = 0; i < this._numMeshes; i++) {
                    var impostor = this._impostors[i];
                    if (!impostor) {
                        continue;
                    }
                    if (impostor.isDisposed) {
                        this.hideImpostor(this._impostors[i--]);
                    }
                    else {
                        var mesh = this._meshes[i];
                        if (mesh && plugin) {
                            plugin.syncMeshWithImpostor(mesh, impostor);
                        }
                    }
                }
            };
            /**
             * Renders a specified physic impostor
             * @param impostor defines the impostor to render
             */
            PhysicsViewer.prototype.showImpostor = function (impostor) {
                if (!this._scene) {
                    return;
                }
                for (var i = 0; i < this._numMeshes; i++) {
                    if (this._impostors[i] == impostor) {
                        return;
                    }
                }
                var debugMesh = this._getDebugMesh(impostor, this._scene);
                if (debugMesh) {
                    this._impostors[this._numMeshes] = impostor;
                    this._meshes[this._numMeshes] = debugMesh;
                    if (this._numMeshes === 0) {
                        this._renderFunction = this._updateDebugMeshes.bind(this);
                        this._scene.registerBeforeRender(this._renderFunction);
                    }
                    this._numMeshes++;
                }
            };
            /**
             * Hides a specified physic impostor
             * @param impostor defines the impostor to hide
             */
            PhysicsViewer.prototype.hideImpostor = function (impostor) {
                if (!impostor || !this._scene) {
                    return;
                }
                var removed = false;
                for (var i = 0; i < this._numMeshes; i++) {
                    if (this._impostors[i] == impostor) {
                        var mesh = this._meshes[i];
                        if (!mesh) {
                            continue;
                        }
                        this._scene.removeMesh(mesh);
                        mesh.dispose();
                        this._numMeshes--;
                        if (this._numMeshes > 0) {
                            this._meshes[i] = this._meshes[this._numMeshes];
                            this._impostors[i] = this._impostors[this._numMeshes];
                            this._meshes[this._numMeshes] = null;
                            this._impostors[this._numMeshes] = null;
                        }
                        else {
                            this._meshes[0] = null;
                            this._impostors[0] = null;
                        }
                        removed = true;
                        break;
                    }
                }
                if (removed && this._numMeshes === 0) {
                    this._scene.unregisterBeforeRender(this._renderFunction);
                }
            };
            PhysicsViewer.prototype._getDebugMaterial = function (scene) {
                if (!this._debugMaterial) {
                    this._debugMaterial = new BABYLON.StandardMaterial('', scene);
                    this._debugMaterial.wireframe = true;
                }
                return this._debugMaterial;
            };
            PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
                if (!this._debugBoxMesh) {
                    this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
                    this._debugBoxMesh.renderingGroupId = 1;
                    this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
                    this._debugBoxMesh.material = this._getDebugMaterial(scene);
                    scene.removeMesh(this._debugBoxMesh);
                }
                return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
            };
            PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
                if (!this._debugSphereMesh) {
                    this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
                    this._debugSphereMesh.renderingGroupId = 1;
                    this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
                    this._debugSphereMesh.material = this._getDebugMaterial(scene);
                    scene.removeMesh(this._debugSphereMesh);
                }
                return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
            };
            PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
                var mesh = null;
                if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
                    mesh = this._getDebugBoxMesh(scene);
                    impostor.getBoxSizeToRef(mesh.scaling);
                }
                else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
                    mesh = this._getDebugSphereMesh(scene);
                    var radius = impostor.getRadius();
                    mesh.scaling.x = radius * 2;
                    mesh.scaling.y = radius * 2;
                    mesh.scaling.z = radius * 2;
                }
                return mesh;
            };
            /** Releases all resources */
            PhysicsViewer.prototype.dispose = function () {
                for (var i = 0; i < this._numMeshes; i++) {
                    this.hideImpostor(this._impostors[i]);
                }
                if (this._debugBoxMesh) {
                    this._debugBoxMesh.dispose();
                }
                if (this._debugSphereMesh) {
                    this._debugSphereMesh.dispose();
                }
                if (this._debugMaterial) {
                    this._debugMaterial.dispose();
                }
                this._impostors.length = 0;
                this._scene = null;
                this._physicsEnginePlugin = null;
            };
            return PhysicsViewer;
        }());
        Debug.PhysicsViewer = PhysicsViewer;
    })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.physicsViewer.js.map

var BABYLON;
(function (BABYLON) {
    Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
        get: function () {
            return this._forceShowBoundingBoxes || false;
        },
        set: function (value) {
            this._forceShowBoundingBoxes = value;
            // Lazyly creates a BB renderer if needed.
            if (value) {
                this.getBoundingBoxRenderer();
            }
        },
        enumerable: true,
        configurable: true
    });
    BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
        if (!this._boundingBoxRenderer) {
            this._boundingBoxRenderer = new BoundingBoxRenderer(this);
        }
        return this._boundingBoxRenderer;
    };
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
        get: function () {
            return this._showBoundingBox || false;
        },
        set: function (value) {
            this._showBoundingBox = value;
            // Lazyly creates a BB renderer if needed.
            if (value) {
                this.getScene().getBoundingBoxRenderer();
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Component responsible of rendering the bounding box of the meshes in a scene.
     * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
     */
    var BoundingBoxRenderer = /** @class */ (function () {
        /**
         * Instantiates a new bounding box renderer in a scene.
         * @param scene the scene the  renderer renders in
         */
        function BoundingBoxRenderer(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
            /**
             * Color of the bounding box lines placed in front of an object
             */
            this.frontColor = new BABYLON.Color3(1, 1, 1);
            /**
             * Color of the bounding box lines placed behind an object
             */
            this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
            /**
             * Defines if the renderer should show the back lines or not
             */
            this.showBackLines = true;
            /**
             * @hidden
             */
            this.renderList = new BABYLON.SmartArray(32);
            this._vertexBuffers = {};
            this.scene = scene;
            scene._addComponent(this);
        }
        /**
         * Registers the component in a given scene
         */
        BoundingBoxRenderer.prototype.register = function () {
            this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
            this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
            this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
            this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
        };
        BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
            if (mesh.showSubMeshesBoundingBox) {
                var boundingInfo = subMesh.getBoundingInfo();
                if (boundingInfo !== null && boundingInfo !== undefined) {
                    boundingInfo.boundingBox._tag = mesh.renderingGroupId;
                    this.renderList.push(boundingInfo.boundingBox);
                }
            }
        };
        BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
            if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
                var boundingInfo = sourceMesh.getBoundingInfo();
                boundingInfo.boundingBox._tag = mesh.renderingGroupId;
                this.renderList.push(boundingInfo.boundingBox);
            }
        };
        BoundingBoxRenderer.prototype._prepareRessources = function () {
            if (this._colorShader) {
                return;
            }
            this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
                attributes: [BABYLON.VertexBuffer.PositionKind],
                uniforms: ["world", "viewProjection", "color"]
            });
            var engine = this.scene.getEngine();
            var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
            this._createIndexBuffer();
        };
        BoundingBoxRenderer.prototype._createIndexBuffer = function () {
            var engine = this.scene.getEngine();
            this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        BoundingBoxRenderer.prototype.rebuild = function () {
            var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vb) {
                vb._rebuild();
            }
            this._createIndexBuffer();
        };
        /**
         * @hidden
         */
        BoundingBoxRenderer.prototype.reset = function () {
            this.renderList.reset();
        };
        /**
         * Render the bounding boxes of a specific rendering group
         * @param renderingGroupId defines the rendering group to render
         */
        BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
            if (this.renderList.length === 0) {
                return;
            }
            this._prepareRessources();
            if (!this._colorShader.isReady()) {
                return;
            }
            var engine = this.scene.getEngine();
            engine.setDepthWrite(false);
            this._colorShader._preBind();
            for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
                var boundingBox = this.renderList.data[boundingBoxIndex];
                if (boundingBox._tag !== renderingGroupId) {
                    continue;
                }
                var min = boundingBox.minimum;
                var max = boundingBox.maximum;
                var diff = max.subtract(min);
                var median = min.add(diff.scale(0.5));
                var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
                    .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
                    .multiply(boundingBox.getWorldMatrix());
                // VBOs
                engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
                if (this.showBackLines) {
                    // Back
                    engine.setDepthFunctionToGreaterOrEqual();
                    this.scene.resetCachedMaterial();
                    this._colorShader.setColor4("color", this.backColor.toColor4());
                    this._colorShader.bind(worldMatrix);
                    // Draw order
                    engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
                }
                // Front
                engine.setDepthFunctionToLess();
                this.scene.resetCachedMaterial();
                this._colorShader.setColor4("color", this.frontColor.toColor4());
                this._colorShader.bind(worldMatrix);
                // Draw order
                engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
            }
            this._colorShader.unbind();
            engine.setDepthFunctionToLessOrEqual();
            engine.setDepthWrite(true);
        };
        /**
         * In case of occlusion queries, we can render the occlusion bounding box through this method
         * @param mesh Define the mesh to render the occlusion bounding box for
         */
        BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
            this._prepareRessources();
            if (!this._colorShader.isReady() || !mesh._boundingInfo) {
                return;
            }
            var engine = this.scene.getEngine();
            engine.setDepthWrite(false);
            engine.setColorWrite(false);
            this._colorShader._preBind();
            var boundingBox = mesh._boundingInfo.boundingBox;
            var min = boundingBox.minimum;
            var max = boundingBox.maximum;
            var diff = max.subtract(min);
            var median = min.add(diff.scale(0.5));
            var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
                .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
                .multiply(boundingBox.getWorldMatrix());
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
            engine.setDepthFunctionToLess();
            this.scene.resetCachedMaterial();
            this._colorShader.bind(worldMatrix);
            engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
            this._colorShader.unbind();
            engine.setDepthFunctionToLessOrEqual();
            engine.setDepthWrite(true);
            engine.setColorWrite(true);
        };
        /**
         * Dispose and release the resources attached to this renderer.
         */
        BoundingBoxRenderer.prototype.dispose = function () {
            if (!this._colorShader) {
                return;
            }
            this.renderList.dispose();
            this._colorShader.dispose();
            var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            this.scene.getEngine()._releaseBuffer(this._indexBuffer);
        };
        return BoundingBoxRenderer;
    }());
    BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boundingBoxRenderer.js.map

var BABYLON;
(function (BABYLON) {
    BABYLON.Engine.prototype.createTransformFeedback = function () {
        return this._gl.createTransformFeedback();
    };
    BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
        this._gl.deleteTransformFeedback(value);
    };
    BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
        this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
    };
    BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
        if (usePoints === void 0) { usePoints = true; }
        this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
    };
    BABYLON.Engine.prototype.endTransformFeedback = function () {
        this._gl.endTransformFeedback();
    };
    BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
        this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
    };
    BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
        this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
    };
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.engine.transformFeedback.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * This represents a GPU particle system in Babylon
     * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
     * @see https://www.babylonjs-playground.com/#PU4WYI#4
     */
    var GPUParticleSystem = /** @class */ (function (_super) {
        __extends(GPUParticleSystem, _super);
        /**
         * Instantiates a GPU particle system.
         * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
         * @param name The name of the particle system
         * @param options The options used to create the system
         * @param scene The scene the particle system belongs to
         * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
         */
        function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
            if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
            var _this = _super.call(this, name) || this;
            /**
             * The layer mask we are rendering the particles through.
             */
            _this.layerMask = 0x0FFFFFFF;
            _this._accumulatedCount = 0;
            _this._targetIndex = 0;
            _this._currentRenderId = -1;
            _this._started = false;
            _this._stopped = false;
            _this._timeDelta = 0;
            _this._attributesStrideSize = 21;
            _this._actualFrame = 0;
            _this._rawTextureWidth = 256;
            /**
            * An event triggered when the system is disposed.
            */
            _this.onDisposeObservable = new BABYLON.Observable();
            /**
             * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
             * to override the particles.
             */
            _this.forceDepthWrite = false;
            _this._preWarmDone = false;
            _this._scene = scene || BABYLON.Engine.LastCreatedScene;
            // Setup the default processing configuration to the scene.
            _this._attachImageProcessingConfiguration(null);
            _this._engine = _this._scene.getEngine();
            if (!options.randomTextureSize) {
                delete options.randomTextureSize;
            }
            var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
            var optionsAsNumber = options;
            if (isFinite(optionsAsNumber)) {
                fullOptions.capacity = optionsAsNumber;
            }
            _this._capacity = fullOptions.capacity;
            _this._activeCount = fullOptions.capacity;
            _this._currentActiveCount = 0;
            _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
            _this._scene.particleSystems.push(_this);
            _this._updateEffectOptions = {
                attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
                uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
                    "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
                    "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
                uniformBuffersNames: [],
                samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
                defines: "",
                fallbacks: null,
                onCompiled: null,
                onError: null,
                indexParameters: null,
                maxSimultaneousLights: 0,
                transformFeedbackVaryings: []
            };
            _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
            // Random data
            var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
            var d = [];
            for (var i = 0; i < maxTextureSize; ++i) {
                d.push(Math.random());
                d.push(Math.random());
                d.push(Math.random());
                d.push(Math.random());
            }
            _this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
            _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            d = [];
            for (var i = 0; i < maxTextureSize; ++i) {
                d.push(Math.random());
                d.push(Math.random());
                d.push(Math.random());
                d.push(Math.random());
            }
            _this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, _this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
            _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            _this._randomTextureSize = maxTextureSize;
            return _this;
        }
        Object.defineProperty(GPUParticleSystem, "IsSupported", {
            /**
             * Gets a boolean indicating if the GPU particles can be rendered on current browser
             */
            get: function () {
                if (!BABYLON.Engine.LastCreatedEngine) {
                    return false;
                }
                return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the maximum number of particles active at the same time.
         * @returns The max number of active particles.
         */
        GPUParticleSystem.prototype.getCapacity = function () {
            return this._capacity;
        };
        Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
            /**
             * Gets or set the number of active particles
             */
            get: function () {
                return this._activeCount;
            },
            set: function (value) {
                this._activeCount = Math.min(value, this._capacity);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Is this system ready to be used/rendered
         * @return true if the system is ready
         */
        GPUParticleSystem.prototype.isReady = function () {
            if (!this._updateEffect) {
                this._recreateUpdateEffect();
                this._recreateRenderEffect();
                return false;
            }
            if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
                return false;
            }
            return true;
        };
        /**
         * Gets if the system has been started. (Note: this will still be true after stop is called)
         * @returns True if it has been started, otherwise false.
         */
        GPUParticleSystem.prototype.isStarted = function () {
            return this._started;
        };
        /**
         * Starts the particle system and begins to emit
         * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
         */
        GPUParticleSystem.prototype.start = function (delay) {
            var _this = this;
            if (delay === void 0) { delay = this.startDelay; }
            if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
                throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
            }
            if (delay) {
                setTimeout(function () {
                    _this.start(0);
                }, delay);
                return;
            }
            this._started = true;
            this._stopped = false;
            this._preWarmDone = false;
            // Animations
            if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
                this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
            }
        };
        /**
         * Stops the particle system.
         */
        GPUParticleSystem.prototype.stop = function () {
            this._stopped = true;
        };
        /**
         * Remove all active particles
         */
        GPUParticleSystem.prototype.reset = function () {
            this._releaseBuffers();
            this._releaseVAOs();
            this._currentActiveCount = 0;
            this._targetIndex = 0;
        };
        /**
         * Returns the string "GPUParticleSystem"
         * @returns a string containing the class name
         */
        GPUParticleSystem.prototype.getClassName = function () {
            return "GPUParticleSystem";
        };
        GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
            _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
            this._releaseBuffers();
            return this;
        };
        /**
         * Adds a new color gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param color1 defines the color to affect to the specified gradient
         * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
            if (!this._colorGradients) {
                this._colorGradients = [];
            }
            var colorGradient = new BABYLON.ColorGradient();
            colorGradient.gradient = gradient;
            colorGradient.color1 = color1;
            this._colorGradients.push(colorGradient);
            this._colorGradients.sort(function (a, b) {
                if (a.gradient < b.gradient) {
                    return -1;
                }
                else if (a.gradient > b.gradient) {
                    return 1;
                }
                return 0;
            });
            if (this._colorGradientsTexture) {
                this._colorGradientsTexture.dispose();
                this._colorGradientsTexture = null;
            }
            this._releaseBuffers();
            return this;
        };
        /**
         * Remove a specific color gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
            this._colorGradientsTexture = null;
            return this;
        };
        GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
            var valueGradient = new BABYLON.FactorGradient();
            valueGradient.gradient = gradient;
            valueGradient.factor1 = factor;
            factorGradients.push(valueGradient);
            factorGradients.sort(function (a, b) {
                if (a.gradient < b.gradient) {
                    return -1;
                }
                else if (a.gradient > b.gradient) {
                    return 1;
                }
                return 0;
            });
            this._releaseBuffers();
        };
        /**
         * Adds a new size gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the size factor to affect to the specified gradient
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
            if (!this._sizeGradients) {
                this._sizeGradients = [];
            }
            this._addFactorGradient(this._sizeGradients, gradient, factor);
            if (this._sizeGradientsTexture) {
                this._sizeGradientsTexture.dispose();
                this._sizeGradientsTexture = null;
            }
            this._releaseBuffers();
            return this;
        };
        /**
         * Remove a specific size gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
            this._sizeGradientsTexture = null;
            return this;
        };
        /**
         * Adds a new angular speed gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the angular speed to affect to the specified gradient
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
            if (!this._angularSpeedGradients) {
                this._angularSpeedGradients = [];
            }
            this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
            if (this._angularSpeedGradientsTexture) {
                this._angularSpeedGradientsTexture.dispose();
                this._angularSpeedGradientsTexture = null;
            }
            this._releaseBuffers();
            return this;
        };
        /**
         * Remove a specific angular speed gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
            this._angularSpeedGradientsTexture = null;
            return this;
        };
        /**
         * Adds a new velocity gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the velocity to affect to the specified gradient
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
            if (!this._velocityGradients) {
                this._velocityGradients = [];
            }
            this._addFactorGradient(this._velocityGradients, gradient, factor);
            if (this._velocityGradientsTexture) {
                this._velocityGradientsTexture.dispose();
                this._velocityGradientsTexture = null;
            }
            this._releaseBuffers();
            return this;
        };
        /**
         * Remove a specific velocity gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
            this._velocityGradientsTexture = null;
            return this;
        };
        /**
         * Adds a new limit velocity gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the limit velocity value to affect to the specified gradient
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
            if (!this._limitVelocityGradients) {
                this._limitVelocityGradients = [];
            }
            this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
            if (this._limitVelocityGradientsTexture) {
                this._limitVelocityGradientsTexture.dispose();
                this._limitVelocityGradientsTexture = null;
            }
            this._releaseBuffers();
            return this;
        };
        /**
         * Remove a specific limit velocity gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
            this._limitVelocityGradientsTexture = null;
            return this;
        };
        /**
         * Adds a new drag gradient
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the drag value to affect to the specified gradient
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
            if (!this._dragGradients) {
                this._dragGradients = [];
            }
            this._addFactorGradient(this._dragGradients, gradient, factor);
            if (this._dragGradientsTexture) {
                this._dragGradientsTexture.dispose();
                this._dragGradientsTexture = null;
            }
            this._releaseBuffers();
            return this;
        };
        /**
         * Remove a specific drag gradient
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
            this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
            this._dragGradientsTexture = null;
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the emit rate value to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
            // Do nothing as emit rate is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
            // Do nothing as emit rate is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the start size value to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
            // Do nothing as start size is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
            // Do nothing as start size is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param min defines the color remap minimal range
         * @param max defines the color remap maximal range
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
            // Do nothing as start size is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
            // Do nothing as start size is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param min defines the alpha remap minimal range
         * @param max defines the alpha remap maximal range
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
            // Do nothing as start size is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
            // Do nothing as start size is not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param color defines the color to affect to the specified gradient
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
            //Not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
            //Not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @returns the list of ramp gradients
         */
        GPUParticleSystem.prototype.getRampGradients = function () {
            return null;
        };
        Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
            /**
             * Not supported by GPUParticleSystem
             * Gets or sets a boolean indicating that ramp gradients must be used
             * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
             */
            get: function () {
                //Not supported by GPUParticleSystem
                return false;
            },
            set: function (value) {
                //Not supported by GPUParticleSystem
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to use (between 0 and 1)
         * @param factor defines the life time factor to affect to the specified gradient
         * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
            //Not supported by GPUParticleSystem
            return this;
        };
        /**
         * Not supported by GPUParticleSystem
         * @param gradient defines the gradient to remove
         * @returns the current particle system
         */
        GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
            //Not supported by GPUParticleSystem
            return this;
        };
        GPUParticleSystem.prototype._reset = function () {
            this._releaseBuffers();
        };
        GPUParticleSystem.prototype._createUpdateVAO = function (source) {
            var updateVertexBuffers = {};
            updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
            updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
            updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
            updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
            updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
            var offset = 12;
            if (!this._colorGradientsTexture) {
                updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
                offset += 4;
            }
            updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
            offset += 3;
            if (!this._isBillboardBased) {
                updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
                offset += 3;
            }
            if (this._angularSpeedGradientsTexture) {
                updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
                offset += 1;
            }
            else {
                updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
                offset += 2;
            }
            if (this._isAnimationSheetEnabled) {
                updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
                offset += 1;
                if (this.spriteRandomStartCell) {
                    updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
                    offset += 1;
                }
            }
            if (this.noiseTexture) {
                updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
                offset += 3;
                updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
                offset += 3;
            }
            var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
            this._engine.bindArrayBuffer(null);
            return vao;
        };
        GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
            var renderVertexBuffers = {};
            renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
            renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
            renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
            renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
            var offset = 12;
            if (!this._colorGradientsTexture) {
                renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
                offset += 4;
            }
            if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
                renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
            }
            offset += 3; // Direction
            if (!this._isBillboardBased) {
                renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
                offset += 3;
            }
            renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
            if (this._angularSpeedGradientsTexture) {
                offset++;
            }
            else {
                offset += 2;
            }
            if (this._isAnimationSheetEnabled) {
                renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
                offset += 1;
                if (this.spriteRandomStartCell) {
                    renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
                    offset += 1;
                }
            }
            if (this.noiseTexture) {
                renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
                offset += 3;
                renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
                offset += 3;
            }
            renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
            renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
            var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
            this._engine.bindArrayBuffer(null);
            return vao;
        };
        GPUParticleSystem.prototype._initialize = function (force) {
            if (force === void 0) { force = false; }
            if (this._buffer0 && !force) {
                return;
            }
            var engine = this._scene.getEngine();
            var data = new Array();
            if (!this.isBillboardBased) {
                this._attributesStrideSize += 3;
            }
            if (this._colorGradientsTexture) {
                this._attributesStrideSize -= 4;
            }
            if (this._angularSpeedGradientsTexture) {
                this._attributesStrideSize -= 1;
            }
            if (this._isAnimationSheetEnabled) {
                this._attributesStrideSize += 1;
                if (this.spriteRandomStartCell) {
                    this._attributesStrideSize += 1;
                }
            }
            if (this.noiseTexture) {
                this._attributesStrideSize += 6;
            }
            for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
                // position
                data.push(0.0);
                data.push(0.0);
                data.push(0.0);
                // Age and life
                data.push(0.0); // create the particle as a dead one to create a new one at start
                data.push(0.0);
                // Seed
                data.push(Math.random());
                data.push(Math.random());
                data.push(Math.random());
                data.push(Math.random());
                // Size
                data.push(0.0);
                data.push(0.0);
                data.push(0.0);
                if (!this._colorGradientsTexture) {
                    // color
                    data.push(0.0);
                    data.push(0.0);
                    data.push(0.0);
                    data.push(0.0);
                }
                // direction
                data.push(0.0);
                data.push(0.0);
                data.push(0.0);
                if (!this.isBillboardBased) {
                    // initialDirection
                    data.push(0.0);
                    data.push(0.0);
                    data.push(0.0);
                }
                // angle
                data.push(0.0);
                if (!this._angularSpeedGradientsTexture) {
                    data.push(0.0);
                }
                if (this._isAnimationSheetEnabled) {
                    data.push(0.0);
                    if (this.spriteRandomStartCell) {
                        data.push(0.0);
                    }
                }
                if (this.noiseTexture) { // Random coordinates for reading into noise texture
                    data.push(Math.random());
                    data.push(Math.random());
                    data.push(Math.random());
                    data.push(Math.random());
                    data.push(Math.random());
                    data.push(Math.random());
                }
            }
            // Sprite data
            var spriteData = new Float32Array([0.5, 0.5, 1, 1,
                -0.5, 0.5, 0, 1,
                -0.5, -0.5, 0, 0,
                0.5, -0.5, 1, 0]);
            // Buffers
            this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
            this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
            this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
            // Update VAO
            this._updateVAO = [];
            this._updateVAO.push(this._createUpdateVAO(this._buffer0));
            this._updateVAO.push(this._createUpdateVAO(this._buffer1));
            // Render VAO
            this._renderVAO = [];
            this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
            this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
            // Links
            this._sourceBuffer = this._buffer0;
            this._targetBuffer = this._buffer1;
        };
        /** @hidden */
        GPUParticleSystem.prototype._recreateUpdateEffect = function () {
            var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
            if (this._isBillboardBased) {
                defines += "\n#define BILLBOARD";
            }
            if (this._colorGradientsTexture) {
                defines += "\n#define COLORGRADIENTS";
            }
            if (this._sizeGradientsTexture) {
                defines += "\n#define SIZEGRADIENTS";
            }
            if (this._angularSpeedGradientsTexture) {
                defines += "\n#define ANGULARSPEEDGRADIENTS";
            }
            if (this._velocityGradientsTexture) {
                defines += "\n#define VELOCITYGRADIENTS";
            }
            if (this._limitVelocityGradientsTexture) {
                defines += "\n#define LIMITVELOCITYGRADIENTS";
            }
            if (this._dragGradientsTexture) {
                defines += "\n#define DRAGGRADIENTS";
            }
            if (this.isAnimationSheetEnabled) {
                defines += "\n#define ANIMATESHEET";
                if (this.spriteRandomStartCell) {
                    defines += "\n#define ANIMATESHEETRANDOMSTART";
                }
            }
            if (this.noiseTexture) {
                defines += "\n#define NOISE";
            }
            if (this._updateEffect && this._updateEffectOptions.defines === defines) {
                return;
            }
            this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
            if (!this._colorGradientsTexture) {
                this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
            }
            this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
            if (!this._isBillboardBased) {
                this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
            }
            this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
            if (this.isAnimationSheetEnabled) {
                this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
                if (this.spriteRandomStartCell) {
                    this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
                }
            }
            if (this.noiseTexture) {
                this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
                this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
            }
            this._updateEffectOptions.defines = defines;
            this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
        };
        /** @hidden */
        GPUParticleSystem.prototype._recreateRenderEffect = function () {
            var defines = "";
            if (this._scene.clipPlane) {
                defines = "\n#define CLIPPLANE";
            }
            if (this._scene.clipPlane2) {
                defines = "\n#define CLIPPLANE2";
            }
            if (this._scene.clipPlane3) {
                defines = "\n#define CLIPPLANE3";
            }
            if (this._scene.clipPlane4) {
                defines = "\n#define CLIPPLANE4";
            }
            if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
                defines = "\n#define BLENDMULTIPLYMODE";
            }
            if (this._isBillboardBased) {
                defines += "\n#define BILLBOARD";
                switch (this.billboardMode) {
                    case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
                        defines += "\n#define BILLBOARDY";
                        break;
                    case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
                        defines += "\n#define BILLBOARDSTRETCHED";
                        break;
                    case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
                    default:
                        break;
                }
            }
            if (this._colorGradientsTexture) {
                defines += "\n#define COLORGRADIENTS";
            }
            if (this.isAnimationSheetEnabled) {
                defines += "\n#define ANIMATESHEET";
            }
            if (this._imageProcessingConfiguration) {
                this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
                defines += "\n" + this._imageProcessingConfigurationDefines.toString();
            }
            if (this._renderEffect && this._renderEffect.defines === defines) {
                return;
            }
            var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
            var samplers = ["textureSampler", "colorGradientSampler"];
            if (BABYLON.ImageProcessingConfiguration) {
                BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
                BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
            }
            this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
        };
        /**
         * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
         * @param preWarm defines if we are in the pre-warmimg phase
         */
        GPUParticleSystem.prototype.animate = function (preWarm) {
            if (preWarm === void 0) { preWarm = false; }
            this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
            this._actualFrame += this._timeDelta;
            if (!this._stopped) {
                if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
                    this.stop();
                }
            }
        };
        GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
            var texture = this[textureName];
            if (!factorGradients || !factorGradients.length || texture) {
                return;
            }
            var data = new Float32Array(this._rawTextureWidth);
            for (var x = 0; x < this._rawTextureWidth; x++) {
                var ratio = x / this._rawTextureWidth;
                BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
                    data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
                });
            }
            this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
        };
        GPUParticleSystem.prototype._createSizeGradientTexture = function () {
            this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
        };
        GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
            this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
        };
        GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
            this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
        };
        GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
            this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
        };
        GPUParticleSystem.prototype._createDragGradientTexture = function () {
            this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
        };
        GPUParticleSystem.prototype._createColorGradientTexture = function () {
            if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
                return;
            }
            var data = new Uint8Array(this._rawTextureWidth * 4);
            var tmpColor = BABYLON.Tmp.Color4[0];
            for (var x = 0; x < this._rawTextureWidth; x++) {
                var ratio = x / this._rawTextureWidth;
                BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
                    BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
                    data[x * 4] = tmpColor.r * 255;
                    data[x * 4 + 1] = tmpColor.g * 255;
                    data[x * 4 + 2] = tmpColor.b * 255;
                    data[x * 4 + 3] = tmpColor.a * 255;
                });
            }
            this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
        };
        /**
         * Renders the particle system in its current state
         * @param preWarm defines if the system should only update the particles but not render them
         * @returns the current number of particles
         */
        GPUParticleSystem.prototype.render = function (preWarm) {
            if (preWarm === void 0) { preWarm = false; }
            if (!this._started) {
                return 0;
            }
            this._createColorGradientTexture();
            this._createSizeGradientTexture();
            this._createAngularSpeedGradientTexture();
            this._createVelocityGradientTexture();
            this._createLimitVelocityGradientTexture();
            this._createDragGradientTexture();
            this._recreateUpdateEffect();
            this._recreateRenderEffect();
            if (!this.isReady()) {
                return 0;
            }
            if (!preWarm) {
                if (!this._preWarmDone && this.preWarmCycles) {
                    for (var index = 0; index < this.preWarmCycles; index++) {
                        this.animate(true);
                        this.render(true);
                    }
                    this._preWarmDone = true;
                }
                if (this._currentRenderId === this._scene.getRenderId()) {
                    return 0;
                }
                this._currentRenderId = this._scene.getRenderId();
            }
            // Get everything ready to render
            this._initialize();
            this._accumulatedCount += this.emitRate * this._timeDelta;
            if (this._accumulatedCount > 1) {
                var intPart = this._accumulatedCount | 0;
                this._accumulatedCount -= intPart;
                this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
            }
            if (!this._currentActiveCount) {
                return 0;
            }
            // Enable update effect
            this._engine.enableEffect(this._updateEffect);
            this._engine.setState(false);
            this._updateEffect.setFloat("currentCount", this._currentActiveCount);
            this._updateEffect.setFloat("timeDelta", this._timeDelta);
            this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
            this._updateEffect.setTexture("randomSampler", this._randomTexture);
            this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
            this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
            this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
            if (!this._colorGradientsTexture) {
                this._updateEffect.setDirectColor4("color1", this.color1);
                this._updateEffect.setDirectColor4("color2", this.color2);
            }
            this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
            this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
            this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
            this._updateEffect.setVector3("gravity", this.gravity);
            if (this._sizeGradientsTexture) {
                this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
            }
            if (this._angularSpeedGradientsTexture) {
                this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
            }
            if (this._velocityGradientsTexture) {
                this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
            }
            if (this._limitVelocityGradientsTexture) {
                this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
                this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
            }
            if (this._dragGradientsTexture) {
                this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
            }
            if (this.particleEmitterType) {
                this.particleEmitterType.applyToShader(this._updateEffect);
            }
            if (this._isAnimationSheetEnabled) {
                this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
            }
            if (this.noiseTexture) {
                this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
                this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
            }
            var emitterWM;
            if (this.emitter.position) {
                var emitterMesh = this.emitter;
                emitterWM = emitterMesh.getWorldMatrix();
            }
            else {
                var emitterPosition = this.emitter;
                emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
            }
            this._updateEffect.setMatrix("emitterWM", emitterWM);
            // Bind source VAO
            this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
            // Update
            this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
            this._engine.setRasterizerState(false);
            this._engine.beginTransformFeedback(true);
            this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
            this._engine.endTransformFeedback();
            this._engine.setRasterizerState(true);
            this._engine.bindTransformFeedbackBuffer(null);
            if (!preWarm) {
                // Enable render effect
                this._engine.enableEffect(this._renderEffect);
                var viewMatrix = this._scene.getViewMatrix();
                this._renderEffect.setMatrix("view", viewMatrix);
                this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
                this._renderEffect.setTexture("textureSampler", this.particleTexture);
                this._renderEffect.setVector2("translationPivot", this.translationPivot);
                if (this._colorGradientsTexture) {
                    this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
                }
                else {
                    this._renderEffect.setDirectColor4("colorDead", this.colorDead);
                }
                if (this._isAnimationSheetEnabled && this.particleTexture) {
                    var baseSize = this.particleTexture.getBaseSize();
                    this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
                }
                if (this._isBillboardBased) {
                    var camera = this._scene.activeCamera;
                    this._renderEffect.setVector3("eyePosition", camera.globalPosition);
                }
                if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
                    var invView = viewMatrix.clone();
                    invView.invert();
                    this._renderEffect.setMatrix("invView", invView);
                    BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
                }
                // image processing
                if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
                    this._imageProcessingConfiguration.bind(this._renderEffect);
                }
                // Draw order
                switch (this.blendMode) {
                    case BABYLON.ParticleSystem.BLENDMODE_ADD:
                        this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
                        break;
                    case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
                        this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
                        break;
                    case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
                        this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                        break;
                    case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
                        this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
                        break;
                }
                if (this.forceDepthWrite) {
                    this._engine.setDepthWrite(true);
                }
                // Bind source VAO
                this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
                // Render
                this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
                this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            }
            // Switch VAOs
            this._targetIndex++;
            if (this._targetIndex === 2) {
                this._targetIndex = 0;
            }
            // Switch buffers
            var tmpBuffer = this._sourceBuffer;
            this._sourceBuffer = this._targetBuffer;
            this._targetBuffer = tmpBuffer;
            return this._currentActiveCount;
        };
        /**
         * Rebuilds the particle system
         */
        GPUParticleSystem.prototype.rebuild = function () {
            this._initialize(true);
        };
        GPUParticleSystem.prototype._releaseBuffers = function () {
            if (this._buffer0) {
                this._buffer0.dispose();
                this._buffer0 = null;
            }
            if (this._buffer1) {
                this._buffer1.dispose();
                this._buffer1 = null;
            }
            if (this._spriteBuffer) {
                this._spriteBuffer.dispose();
                this._spriteBuffer = null;
            }
        };
        GPUParticleSystem.prototype._releaseVAOs = function () {
            if (!this._updateVAO) {
                return;
            }
            for (var index = 0; index < this._updateVAO.length; index++) {
                this._engine.releaseVertexArrayObject(this._updateVAO[index]);
            }
            this._updateVAO = [];
            for (var index = 0; index < this._renderVAO.length; index++) {
                this._engine.releaseVertexArrayObject(this._renderVAO[index]);
            }
            this._renderVAO = [];
        };
        /**
         * Disposes the particle system and free the associated resources
         * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
         */
        GPUParticleSystem.prototype.dispose = function (disposeTexture) {
            if (disposeTexture === void 0) { disposeTexture = true; }
            var index = this._scene.particleSystems.indexOf(this);
            if (index > -1) {
                this._scene.particleSystems.splice(index, 1);
            }
            this._releaseBuffers();
            this._releaseVAOs();
            if (this._colorGradientsTexture) {
                this._colorGradientsTexture.dispose();
                this._colorGradientsTexture = null;
            }
            if (this._sizeGradientsTexture) {
                this._sizeGradientsTexture.dispose();
                this._sizeGradientsTexture = null;
            }
            if (this._angularSpeedGradientsTexture) {
                this._angularSpeedGradientsTexture.dispose();
                this._angularSpeedGradientsTexture = null;
            }
            if (this._velocityGradientsTexture) {
                this._velocityGradientsTexture.dispose();
                this._velocityGradientsTexture = null;
            }
            if (this._limitVelocityGradientsTexture) {
                this._limitVelocityGradientsTexture.dispose();
                this._limitVelocityGradientsTexture = null;
            }
            if (this._dragGradientsTexture) {
                this._dragGradientsTexture.dispose();
                this._dragGradientsTexture = null;
            }
            if (this._randomTexture) {
                this._randomTexture.dispose();
                this._randomTexture = null;
            }
            if (this._randomTexture2) {
                this._randomTexture2.dispose();
                this._randomTexture2 = null;
            }
            if (disposeTexture && this.particleTexture) {
                this.particleTexture.dispose();
                this.particleTexture = null;
            }
            if (disposeTexture && this.noiseTexture) {
                this.noiseTexture.dispose();
                this.noiseTexture = null;
            }
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
        };
        /**
         * Clones the particle system.
         * @param name The name of the cloned object
         * @param newEmitter The new emitter to use
         * @returns the cloned particle system
         */
        GPUParticleSystem.prototype.clone = function (name, newEmitter) {
            var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
            BABYLON.Tools.DeepCopy(this, result);
            if (newEmitter === undefined) {
                newEmitter = this.emitter;
            }
            result.emitter = newEmitter;
            if (this.particleTexture) {
                result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
            }
            return result;
        };
        /**
         * Serializes the particle system to a JSON object.
         * @returns the JSON object
         */
        GPUParticleSystem.prototype.serialize = function () {
            var serializationObject = {};
            BABYLON.ParticleSystem._Serialize(serializationObject, this);
            serializationObject.activeParticleCount = this.activeParticleCount;
            return serializationObject;
        };
        /**
         * Parses a JSON object to create a GPU particle system.
         * @param parsedParticleSystem The JSON object to parse
         * @param scene The scene to create the particle system in
         * @param rootUrl The root url to use to load external dependencies like texture
         * @param doNotStart Ignore the preventAutoStart attribute and does not start
         * @returns the parsed GPU particle system
         */
        GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
            if (doNotStart === void 0) { doNotStart = false; }
            var name = parsedParticleSystem.name;
            var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
            if (parsedParticleSystem.activeParticleCount) {
                particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
            }
            BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
            // Auto start
            if (parsedParticleSystem.preventAutoStart) {
                particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
            }
            if (!doNotStart && !particleSystem.preventAutoStart) {
                particleSystem.start();
            }
            return particleSystem;
        };
        return GPUParticleSystem;
    }(BABYLON.BaseParticleSystem));
    BABYLON.GPUParticleSystem = GPUParticleSystem;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gpuParticleSystem.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Represents one particle of a solid particle system.
     */
    var SolidParticle = /** @class */ (function () {
        /**
         * Creates a Solid Particle object.
         * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
         * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
         * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
         * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
         * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
         * @param shapeId (integer) is the model shape identifier in the SPS.
         * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
         * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
         */
        function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
            if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
            /**
             * particle global index
             */
            this.idx = 0;
            /**
             * The color of the particle
             */
            this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            /**
             * The world space position of the particle.
             */
            this.position = BABYLON.Vector3.Zero();
            /**
             * The world space rotation of the particle. (Not use if rotationQuaternion is set)
             */
            this.rotation = BABYLON.Vector3.Zero();
            /**
             * The scaling of the particle.
             */
            this.scaling = BABYLON.Vector3.One();
            /**
             * The uvs of the particle.
             */
            this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
            /**
             * The current speed of the particle.
             */
            this.velocity = BABYLON.Vector3.Zero();
            /**
             * The pivot point in the particle local space.
             */
            this.pivot = BABYLON.Vector3.Zero();
            /**
             * Must the particle be translated from its pivot point in its local space ?
             * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
             * Default : false
             */
            this.translateFromPivot = false;
            /**
             * Is the particle active or not ?
             */
            this.alive = true;
            /**
             * Is the particle visible or not ?
             */
            this.isVisible = true;
            /**
             * Index of this particle in the global "positions" array (Internal use)
             * @hidden
             */
            this._pos = 0;
            /**
             * @hidden Index of this particle in the global "indices" array (Internal use)
             */
            this._ind = 0;
            /**
             * ModelShape id of this particle
             */
            this.shapeId = 0;
            /**
             * Index of the particle in its shape id (Internal use)
             */
            this.idxInShape = 0;
            /**
             * @hidden Still set as invisible in order to skip useless computations (Internal use)
             */
            this._stillInvisible = false;
            /**
             * @hidden Last computed particle rotation matrix
             */
            this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
            /**
             * Parent particle Id, if any.
             * Default null.
             */
            this.parentId = null;
            /**
             * @hidden Internal global position in the SPS.
             */
            this._globalPosition = BABYLON.Vector3.Zero();
            this.idx = particleIndex;
            this._pos = positionIndex;
            this._ind = indiceIndex;
            this._model = model;
            this.shapeId = shapeId;
            this.idxInShape = idxInShape;
            this._sps = sps;
            if (modelBoundingInfo) {
                this._modelBoundingInfo = modelBoundingInfo;
                this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
            }
        }
        Object.defineProperty(SolidParticle.prototype, "scale", {
            /**
             * Legacy support, changed scale to scaling
             */
            get: function () {
                return this.scaling;
            },
            /**
             * Legacy support, changed scale to scaling
             */
            set: function (scale) {
                this.scaling = scale;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticle.prototype, "quaternion", {
            /**
             * Legacy support, changed quaternion to rotationQuaternion
             */
            get: function () {
                return this.rotationQuaternion;
            },
            /**
             * Legacy support, changed quaternion to rotationQuaternion
             */
            set: function (q) {
                this.rotationQuaternion = q;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
         * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
         * @param target is the object (solid particle or mesh) what the intersection is computed against.
         * @returns true if it intersects
         */
        SolidParticle.prototype.intersectsMesh = function (target) {
            if (!this._boundingInfo || !target._boundingInfo) {
                return false;
            }
            if (this._sps._bSphereOnly) {
                return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
            }
            return this._boundingInfo.intersects(target._boundingInfo, false);
        };
        return SolidParticle;
    }());
    BABYLON.SolidParticle = SolidParticle;
    /**
     * Represents the shape of the model used by one particle of a solid particle system.
     * SPS internal tool, don't use it manually.
     */
    var ModelShape = /** @class */ (function () {
        /**
         * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
         * SPS internal tool, don't use it manually.
         * @hidden
         */
        function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
            /**
             * length of the shape in the model indices array (internal use)
             * @hidden
             */
            this._indicesLength = 0;
            this.shapeID = id;
            this._shape = shape;
            this._indicesLength = indicesLength;
            this._shapeUV = shapeUV;
            this._positionFunction = posFunction;
            this._vertexFunction = vtxFunction;
        }
        return ModelShape;
    }());
    BABYLON.ModelShape = ModelShape;
    /**
     * Represents a Depth Sorted Particle in the solid particle system.
     */
    var DepthSortedParticle = /** @class */ (function () {
        function DepthSortedParticle() {
            /**
             * Index of the particle in the "indices" array
             */
            this.ind = 0;
            /**
             * Length of the particle shape in the "indices" array
             */
            this.indicesLength = 0;
            /**
             * Squared distance from the particle to the camera
             */
            this.sqDistance = 0.0;
        }
        return DepthSortedParticle;
    }());
    BABYLON.DepthSortedParticle = DepthSortedParticle;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.solidParticle.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
     *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.

     * The SPS is also a particle system. It provides some methods to manage the particles.
     * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
     *
     * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
     */
    var SolidParticleSystem = /** @class */ (function () {
        /**
         * Creates a SPS (Solid Particle System) object.
         * @param name (String) is the SPS name, this will be the underlying mesh name.
         * @param scene (Scene) is the scene in which the SPS is added.
         * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
         * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
         * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
         * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
         * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
         * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
         * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
         */
        function SolidParticleSystem(name, scene, options) {
            /**
             *  The SPS array of Solid Particle objects. Just access each particle as with any classic array.
             *  Example : var p = SPS.particles[i];
             */
            this.particles = new Array();
            /**
             * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
             */
            this.nbParticles = 0;
            /**
             * If the particles must ever face the camera (default false). Useful for planar particles.
             */
            this.billboard = false;
            /**
             * Recompute normals when adding a shape
             */
            this.recomputeNormals = true;
            /**
             * This a counter ofr your own usage. It's not set by any SPS functions.
             */
            this.counter = 0;
            /**
             * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
             * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
             */
            this.vars = {};
            /**
             * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
             * @hidden
             */
            this._bSphereOnly = false;
            /**
             * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
             * @hidden
             */
            this._bSphereRadiusFactor = 1.0;
            this._positions = new Array();
            this._indices = new Array();
            this._normals = new Array();
            this._colors = new Array();
            this._uvs = new Array();
            this._index = 0; // indices index
            this._updatable = true;
            this._pickable = false;
            this._isVisibilityBoxLocked = false;
            this._alwaysVisible = false;
            this._depthSort = false;
            this._shapeCounter = 0;
            this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
            this._color = new BABYLON.Color4(0, 0, 0, 0);
            this._computeParticleColor = true;
            this._computeParticleTexture = true;
            this._computeParticleRotation = true;
            this._computeParticleVertex = false;
            this._computeBoundingBox = false;
            this._depthSortParticles = true;
            this._cam_axisZ = BABYLON.Vector3.Zero();
            this._cam_axisY = BABYLON.Vector3.Zero();
            this._cam_axisX = BABYLON.Vector3.Zero();
            this._axisZ = BABYLON.Axis.Z;
            this._camDir = BABYLON.Vector3.Zero();
            this._camInvertedPosition = BABYLON.Vector3.Zero();
            this._rotMatrix = new BABYLON.Matrix();
            this._invertMatrix = new BABYLON.Matrix();
            this._rotated = BABYLON.Vector3.Zero();
            this._quaternion = new BABYLON.Quaternion();
            this._vertex = BABYLON.Vector3.Zero();
            this._normal = BABYLON.Vector3.Zero();
            this._yaw = 0.0;
            this._pitch = 0.0;
            this._roll = 0.0;
            this._halfroll = 0.0;
            this._halfpitch = 0.0;
            this._halfyaw = 0.0;
            this._sinRoll = 0.0;
            this._cosRoll = 0.0;
            this._sinPitch = 0.0;
            this._cosPitch = 0.0;
            this._sinYaw = 0.0;
            this._cosYaw = 0.0;
            this._mustUnrotateFixedNormals = false;
            this._minimum = BABYLON.Vector3.Zero();
            this._maximum = BABYLON.Vector3.Zero();
            this._minBbox = BABYLON.Vector3.Zero();
            this._maxBbox = BABYLON.Vector3.Zero();
            this._particlesIntersect = false;
            this._depthSortFunction = function (p1, p2) {
                return (p2.sqDistance - p1.sqDistance);
            };
            this._needs32Bits = false;
            this._pivotBackTranslation = BABYLON.Vector3.Zero();
            this._scaledPivot = BABYLON.Vector3.Zero();
            this._particleHasParent = false;
            this.name = name;
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            this._camera = scene.activeCamera;
            this._pickable = options ? options.isPickable : false;
            this._depthSort = options ? options.enableDepthSort : false;
            this._particlesIntersect = options ? options.particleIntersection : false;
            this._bSphereOnly = options ? options.boundingSphereOnly : false;
            this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
            if (options && options.updatable !== undefined) {
                this._updatable = options.updatable;
            }
            else {
                this._updatable = true;
            }
            if (this._pickable) {
                this.pickedParticles = [];
            }
            if (this._depthSort) {
                this.depthSortedParticles = [];
            }
        }
        /**
         * Builds the SPS underlying mesh. Returns a standard Mesh.
         * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
         * @returns the created mesh
         */
        SolidParticleSystem.prototype.buildMesh = function () {
            if (this.nbParticles === 0) {
                var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
                this.addShape(triangle, 1);
                triangle.dispose();
            }
            this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
            this._positions32 = new Float32Array(this._positions);
            this._uvs32 = new Float32Array(this._uvs);
            this._colors32 = new Float32Array(this._colors);
            if (this.recomputeNormals) {
                BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
            }
            this._normals32 = new Float32Array(this._normals);
            this._fixedNormal32 = new Float32Array(this._normals);
            if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
                this._unrotateFixedNormals();
            }
            var vertexData = new BABYLON.VertexData();
            vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
            vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
            vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
            if (this._uvs32.length > 0) {
                vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
            }
            if (this._colors32.length > 0) {
                vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
            }
            var mesh = new BABYLON.Mesh(this.name, this._scene);
            vertexData.applyToMesh(mesh, this._updatable);
            this.mesh = mesh;
            this.mesh.isPickable = this._pickable;
            // free memory
            if (!this._depthSort) {
                this._indices = null;
            }
            this._positions = null;
            this._normals = null;
            this._uvs = null;
            this._colors = null;
            if (!this._updatable) {
                this.particles.length = 0;
            }
            return mesh;
        };
        /**
         * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
         * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
         * Thus the particles generated from `digest()` have their property `position` set yet.
         * @param mesh ( Mesh ) is the mesh to be digested
         * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
         * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
         * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
         * @returns the current SPS
         */
        SolidParticleSystem.prototype.digest = function (mesh, options) {
            var size = (options && options.facetNb) || 1;
            var number = (options && options.number) || 0;
            var delta = (options && options.delta) || 0;
            var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var meshInd = mesh.getIndices();
            var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var f = 0; // facet counter
            var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
            // compute size from number
            if (number) {
                number = (number > totalFacets) ? totalFacets : number;
                size = Math.round(totalFacets / number);
                delta = 0;
            }
            else {
                size = (size > totalFacets) ? totalFacets : size;
            }
            var facetPos = []; // submesh positions
            var facetInd = []; // submesh indices
            var facetUV = []; // submesh UV
            var facetCol = []; // submesh colors
            var barycenter = BABYLON.Vector3.Zero();
            var sizeO = size;
            while (f < totalFacets) {
                size = sizeO + Math.floor((1 + delta) * Math.random());
                if (f > totalFacets - size) {
                    size = totalFacets - f;
                }
                // reset temp arrays
                facetPos.length = 0;
                facetInd.length = 0;
                facetUV.length = 0;
                facetCol.length = 0;
                // iterate over "size" facets
                var fi = 0;
                for (var j = f * 3; j < (f + size) * 3; j++) {
                    facetInd.push(fi);
                    var i = meshInd[j];
                    facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
                    if (meshUV) {
                        facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
                    }
                    if (meshCol) {
                        facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
                    }
                    fi++;
                }
                // create a model shape for each single particle
                var idx = this.nbParticles;
                var shape = this._posToShape(facetPos);
                var shapeUV = this._uvsToShapeUV(facetUV);
                // compute the barycenter of the shape
                var v;
                for (v = 0; v < shape.length; v++) {
                    barycenter.addInPlace(shape[v]);
                }
                barycenter.scaleInPlace(1 / shape.length);
                // shift the shape from its barycenter to the origin
                for (v = 0; v < shape.length; v++) {
                    shape[v].subtractInPlace(barycenter);
                }
                var bInfo;
                if (this._particlesIntersect) {
                    bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
                }
                var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
                // add the particle in the SPS
                var currentPos = this._positions.length;
                var currentInd = this._indices.length;
                this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
                this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
                // initialize the particle position
                this.particles[this.nbParticles].position.addInPlace(barycenter);
                this._index += shape.length;
                idx++;
                this.nbParticles++;
                this._shapeCounter++;
                f += size;
            }
            return this;
        };
        // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
        SolidParticleSystem.prototype._unrotateFixedNormals = function () {
            var index = 0;
            var idx = 0;
            for (var p = 0; p < this.particles.length; p++) {
                this._particle = this.particles[p];
                this._shape = this._particle._model._shape;
                if (this._particle.rotationQuaternion) {
                    this._quaternion.copyFrom(this._particle.rotationQuaternion);
                }
                else {
                    this._yaw = this._particle.rotation.y;
                    this._pitch = this._particle.rotation.x;
                    this._roll = this._particle.rotation.z;
                    this._quaternionRotationYPR();
                }
                this._quaternionToRotationMatrix();
                this._rotMatrix.invertToRef(this._invertMatrix);
                for (var pt = 0; pt < this._shape.length; pt++) {
                    idx = index + pt * 3;
                    BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
                    this._fixedNormal32[idx] = this._normal.x;
                    this._fixedNormal32[idx + 1] = this._normal.y;
                    this._fixedNormal32[idx + 2] = this._normal.z;
                }
                index = idx + 3;
            }
        };
        //reset copy
        SolidParticleSystem.prototype._resetCopy = function () {
            this._copy.position.x = 0;
            this._copy.position.y = 0;
            this._copy.position.z = 0;
            this._copy.rotation.x = 0;
            this._copy.rotation.y = 0;
            this._copy.rotation.z = 0;
            this._copy.rotationQuaternion = null;
            this._copy.scaling.x = 1.0;
            this._copy.scaling.y = 1.0;
            this._copy.scaling.z = 1.0;
            this._copy.uvs.x = 0;
            this._copy.uvs.y = 0;
            this._copy.uvs.z = 1.0;
            this._copy.uvs.w = 1.0;
            this._copy.color = null;
            this._copy.translateFromPivot = false;
        };
        // _meshBuilder : inserts the shape model in the global SPS mesh
        SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
            var i;
            var u = 0;
            var c = 0;
            var n = 0;
            this._resetCopy();
            if (options && options.positionFunction) { // call to custom positionFunction
                options.positionFunction(this._copy, idx, idxInShape);
                this._mustUnrotateFixedNormals = true;
            }
            if (this._copy.rotationQuaternion) {
                this._quaternion.copyFrom(this._copy.rotationQuaternion);
            }
            else {
                this._yaw = this._copy.rotation.y;
                this._pitch = this._copy.rotation.x;
                this._roll = this._copy.rotation.z;
                this._quaternionRotationYPR();
            }
            this._quaternionToRotationMatrix();
            this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
            this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
            this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
            if (this._copy.translateFromPivot) {
                this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
            }
            else {
                this._pivotBackTranslation.copyFrom(this._scaledPivot);
            }
            for (i = 0; i < shape.length; i++) {
                this._vertex.x = shape[i].x;
                this._vertex.y = shape[i].y;
                this._vertex.z = shape[i].z;
                if (options && options.vertexFunction) {
                    options.vertexFunction(this._copy, this._vertex, i);
                }
                this._vertex.x *= this._copy.scaling.x;
                this._vertex.y *= this._copy.scaling.y;
                this._vertex.z *= this._copy.scaling.z;
                this._vertex.x -= this._scaledPivot.x;
                this._vertex.y -= this._scaledPivot.y;
                this._vertex.z -= this._scaledPivot.z;
                BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
                this._rotated.addInPlace(this._pivotBackTranslation);
                positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
                if (meshUV) {
                    uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
                    u += 2;
                }
                if (this._copy.color) {
                    this._color = this._copy.color;
                }
                else if (meshCol && meshCol[c] !== undefined) {
                    this._color.r = meshCol[c];
                    this._color.g = meshCol[c + 1];
                    this._color.b = meshCol[c + 2];
                    this._color.a = meshCol[c + 3];
                }
                else {
                    this._color.r = 1.0;
                    this._color.g = 1.0;
                    this._color.b = 1.0;
                    this._color.a = 1.0;
                }
                colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
                c += 4;
                if (!this.recomputeNormals && meshNor) {
                    this._normal.x = meshNor[n];
                    this._normal.y = meshNor[n + 1];
                    this._normal.z = meshNor[n + 2];
                    BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
                    normals.push(this._normal.x, this._normal.y, this._normal.z);
                    n += 3;
                }
            }
            for (i = 0; i < meshInd.length; i++) {
                var current_ind = p + meshInd[i];
                indices.push(current_ind);
                if (current_ind > 65535) {
                    this._needs32Bits = true;
                }
            }
            if (this._pickable) {
                var nbfaces = meshInd.length / 3;
                for (i = 0; i < nbfaces; i++) {
                    this.pickedParticles.push({ idx: idx, faceId: i });
                }
            }
            if (this._depthSort) {
                this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
            }
            return this._copy;
        };
        // returns a shape array from positions array
        SolidParticleSystem.prototype._posToShape = function (positions) {
            var shape = [];
            for (var i = 0; i < positions.length; i += 3) {
                shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
            }
            return shape;
        };
        // returns a shapeUV array from a Vector4 uvs
        SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
            var shapeUV = [];
            if (uvs) {
                for (var i = 0; i < uvs.length; i++) {
                    shapeUV.push(uvs[i]);
                }
            }
            return shapeUV;
        };
        // adds a new particle object in the particles array
        SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
            if (bInfo === void 0) { bInfo = null; }
            var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
            this.particles.push(sp);
            return sp;
        };
        /**
         * Adds some particles to the SPS from the model shape. Returns the shape id.
         * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
         * @param mesh is any Mesh object that will be used as a model for the solid particles.
         * @param nb (positive integer) the number of particles to be created from this model
         * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
         * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
         * @returns the number of shapes in the system
         */
        SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
            var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var meshInd = mesh.getIndices();
            var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var bbInfo;
            if (this._particlesIntersect) {
                bbInfo = mesh.getBoundingInfo();
            }
            var shape = this._posToShape(meshPos);
            var shapeUV = this._uvsToShapeUV(meshUV);
            var posfunc = options ? options.positionFunction : null;
            var vtxfunc = options ? options.vertexFunction : null;
            var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
            // particles
            var sp;
            var currentCopy;
            var idx = this.nbParticles;
            for (var i = 0; i < nb; i++) {
                var currentPos = this._positions.length;
                var currentInd = this._indices.length;
                currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
                if (this._updatable) {
                    sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
                    sp.position.copyFrom(currentCopy.position);
                    sp.rotation.copyFrom(currentCopy.rotation);
                    if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
                        sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
                    }
                    if (currentCopy.color && sp.color) {
                        sp.color.copyFrom(currentCopy.color);
                    }
                    sp.scaling.copyFrom(currentCopy.scaling);
                    sp.uvs.copyFrom(currentCopy.uvs);
                }
                this._index += shape.length;
                idx++;
            }
            this.nbParticles += nb;
            this._shapeCounter++;
            return this._shapeCounter - 1;
        };
        // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
        SolidParticleSystem.prototype._rebuildParticle = function (particle) {
            this._resetCopy();
            if (particle._model._positionFunction) { // recall to stored custom positionFunction
                particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
            }
            if (this._copy.rotationQuaternion) {
                this._quaternion.copyFrom(this._copy.rotationQuaternion);
            }
            else {
                this._yaw = this._copy.rotation.y;
                this._pitch = this._copy.rotation.x;
                this._roll = this._copy.rotation.z;
                this._quaternionRotationYPR();
            }
            this._quaternionToRotationMatrix();
            this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
            this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
            this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
            if (this._copy.translateFromPivot) {
                this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
            }
            else {
                this._pivotBackTranslation.copyFrom(this._scaledPivot);
            }
            this._shape = particle._model._shape;
            for (var pt = 0; pt < this._shape.length; pt++) {
                this._vertex.x = this._shape[pt].x;
                this._vertex.y = this._shape[pt].y;
                this._vertex.z = this._shape[pt].z;
                if (particle._model._vertexFunction) {
                    particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
                }
                this._vertex.x *= this._copy.scaling.x;
                this._vertex.y *= this._copy.scaling.y;
                this._vertex.z *= this._copy.scaling.z;
                this._vertex.x -= this._scaledPivot.x;
                this._vertex.y -= this._scaledPivot.y;
                this._vertex.z -= this._scaledPivot.z;
                BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
                this._rotated.addInPlace(this._pivotBackTranslation);
                this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
                this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
                this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
            }
            particle.position.x = 0.0;
            particle.position.y = 0.0;
            particle.position.z = 0.0;
            particle.rotation.x = 0.0;
            particle.rotation.y = 0.0;
            particle.rotation.z = 0.0;
            particle.rotationQuaternion = null;
            particle.scaling.x = 1.0;
            particle.scaling.y = 1.0;
            particle.scaling.z = 1.0;
            particle.uvs.x = 0.0;
            particle.uvs.y = 0.0;
            particle.uvs.z = 1.0;
            particle.uvs.w = 1.0;
            particle.pivot.x = 0.0;
            particle.pivot.y = 0.0;
            particle.pivot.z = 0.0;
            particle.translateFromPivot = false;
            particle.parentId = null;
        };
        /**
         * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
         * @returns the SPS.
         */
        SolidParticleSystem.prototype.rebuildMesh = function () {
            for (var p = 0; p < this.particles.length; p++) {
                this._rebuildParticle(this.particles[p]);
            }
            this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
            return this;
        };
        /**
         *  Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
         *  This method calls `updateParticle()` for each particle of the SPS.
         *  For an animated SPS, it is usually called within the render loop.
         * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
         * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
         * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
         * @returns the SPS.
         */
        SolidParticleSystem.prototype.setParticles = function (start, end, update) {
            if (start === void 0) { start = 0; }
            if (end === void 0) { end = this.nbParticles - 1; }
            if (update === void 0) { update = true; }
            if (!this._updatable) {
                return this;
            }
            // custom beforeUpdate
            this.beforeUpdateParticles(start, end, update);
            this._cam_axisX.x = 1.0;
            this._cam_axisX.y = 0.0;
            this._cam_axisX.z = 0.0;
            this._cam_axisY.x = 0.0;
            this._cam_axisY.y = 1.0;
            this._cam_axisY.z = 0.0;
            this._cam_axisZ.x = 0.0;
            this._cam_axisZ.y = 0.0;
            this._cam_axisZ.z = 1.0;
            // cases when the World Matrix is to be computed first
            if (this.billboard || this._depthSort) {
                this.mesh.computeWorldMatrix(true);
                this.mesh._worldMatrix.invertToRef(this._invertMatrix);
            }
            // if the particles will always face the camera
            if (this.billboard) {
                // compute the camera position and un-rotate it by the current mesh rotation
                this._camera.getDirectionToRef(this._axisZ, this._camDir);
                BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
                this._cam_axisZ.normalize();
                // same for camera up vector extracted from the cam view matrix
                var view = this._camera.getViewMatrix(true);
                BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
                BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
                this._cam_axisY.normalize();
                this._cam_axisX.normalize();
            }
            // if depthSort, compute the camera global position in the mesh local system
            if (this._depthSort) {
                BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
            }
            BABYLON.Matrix.IdentityToRef(this._rotMatrix);
            var idx = 0; // current position index in the global array positions32
            var index = 0; // position start index in the global array positions32 of the current particle
            var colidx = 0; // current color index in the global array colors32
            var colorIndex = 0; // color start index in the global array colors32 of the current particle
            var uvidx = 0; // current uv index in the global array uvs32
            var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
            var pt = 0; // current index in the particle model shape
            if (this.mesh.isFacetDataEnabled) {
                this._computeBoundingBox = true;
            }
            end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
            if (this._computeBoundingBox) {
                if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
                    BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
                    BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
                }
                else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
                    if (this.mesh._boundingInfo) {
                        this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
                        this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
                    }
                }
            }
            // particle loop
            index = this.particles[start]._pos;
            var vpos = (index / 3) | 0;
            colorIndex = vpos * 4;
            uvIndex = vpos * 2;
            for (var p = start; p <= end; p++) {
                this._particle = this.particles[p];
                this._shape = this._particle._model._shape;
                this._shapeUV = this._particle._model._shapeUV;
                // call to custom user function to update the particle properties
                this.updateParticle(this._particle);
                // camera-particle distance for depth sorting
                if (this._depthSort && this._depthSortParticles) {
                    var dsp = this.depthSortedParticles[p];
                    dsp.ind = this._particle._ind;
                    dsp.indicesLength = this._particle._model._indicesLength;
                    dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
                }
                // skip the computations for inactive or already invisible particles
                if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
                    // increment indexes for the next particle
                    pt = this._shape.length;
                    index += pt * 3;
                    colorIndex += pt * 4;
                    uvIndex += pt * 2;
                    continue;
                }
                if (this._particle.isVisible) {
                    this._particle._stillInvisible = false; // un-mark permanent invisibility
                    this._particleHasParent = (this._particle.parentId !== null);
                    this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
                    this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
                    this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
                    // particle rotation matrix
                    if (this.billboard) {
                        this._particle.rotation.x = 0.0;
                        this._particle.rotation.y = 0.0;
                    }
                    if (this._computeParticleRotation || this.billboard) {
                        if (this._particle.rotationQuaternion) {
                            this._quaternion.copyFrom(this._particle.rotationQuaternion);
                        }
                        else {
                            this._yaw = this._particle.rotation.y;
                            this._pitch = this._particle.rotation.x;
                            this._roll = this._particle.rotation.z;
                            this._quaternionRotationYPR();
                        }
                        this._quaternionToRotationMatrix();
                    }
                    if (this._particleHasParent) {
                        this._parent = this.particles[this._particle.parentId];
                        this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
                        this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
                        this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
                        this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
                        this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
                        this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
                        if (this._computeParticleRotation || this.billboard) {
                            this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
                            this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
                            this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
                            this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
                            this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
                            this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
                            this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
                            this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
                            this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
                        }
                    }
                    else {
                        this._particle._globalPosition.x = this._particle.position.x;
                        this._particle._globalPosition.y = this._particle.position.y;
                        this._particle._globalPosition.z = this._particle.position.z;
                        if (this._computeParticleRotation || this.billboard) {
                            this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
                            this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
                            this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
                            this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
                            this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
                            this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
                            this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
                            this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
                            this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
                        }
                    }
                    if (this._particle.translateFromPivot) {
                        this._pivotBackTranslation.x = 0.0;
                        this._pivotBackTranslation.y = 0.0;
                        this._pivotBackTranslation.z = 0.0;
                    }
                    else {
                        this._pivotBackTranslation.x = this._scaledPivot.x;
                        this._pivotBackTranslation.y = this._scaledPivot.y;
                        this._pivotBackTranslation.z = this._scaledPivot.z;
                    }
                    // particle vertex loop
                    for (pt = 0; pt < this._shape.length; pt++) {
                        idx = index + pt * 3;
                        colidx = colorIndex + pt * 4;
                        uvidx = uvIndex + pt * 2;
                        this._vertex.x = this._shape[pt].x;
                        this._vertex.y = this._shape[pt].y;
                        this._vertex.z = this._shape[pt].z;
                        if (this._computeParticleVertex) {
                            this.updateParticleVertex(this._particle, this._vertex, pt);
                        }
                        // positions
                        this._vertex.x *= this._particle.scaling.x;
                        this._vertex.y *= this._particle.scaling.y;
                        this._vertex.z *= this._particle.scaling.z;
                        this._vertex.x -= this._scaledPivot.x;
                        this._vertex.y -= this._scaledPivot.y;
                        this._vertex.z -= this._scaledPivot.z;
                        this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
                        this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
                        this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
                        this._rotated.x += this._pivotBackTranslation.x;
                        this._rotated.y += this._pivotBackTranslation.y;
                        this._rotated.z += this._pivotBackTranslation.z;
                        this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                        this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                        this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
                        if (this._computeBoundingBox) {
                            if (this._positions32[idx] < this._minimum.x) {
                                this._minimum.x = this._positions32[idx];
                            }
                            if (this._positions32[idx] > this._maximum.x) {
                                this._maximum.x = this._positions32[idx];
                            }
                            if (this._positions32[idx + 1] < this._minimum.y) {
                                this._minimum.y = this._positions32[idx + 1];
                            }
                            if (this._positions32[idx + 1] > this._maximum.y) {
                                this._maximum.y = this._positions32[idx + 1];
                            }
                            if (this._positions32[idx + 2] < this._minimum.z) {
                                this._minimum.z = this._positions32[idx + 2];
                            }
                            if (this._positions32[idx + 2] > this._maximum.z) {
                                this._maximum.z = this._positions32[idx + 2];
                            }
                        }
                        // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
                        if (!this._computeParticleVertex) {
                            this._normal.x = this._fixedNormal32[idx];
                            this._normal.y = this._fixedNormal32[idx + 1];
                            this._normal.z = this._fixedNormal32[idx + 2];
                            this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
                            this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
                            this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
                            this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                            this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                            this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
                        }
                        if (this._computeParticleColor && this._particle.color) {
                            this._colors32[colidx] = this._particle.color.r;
                            this._colors32[colidx + 1] = this._particle.color.g;
                            this._colors32[colidx + 2] = this._particle.color.b;
                            this._colors32[colidx + 3] = this._particle.color.a;
                        }
                        if (this._computeParticleTexture) {
                            this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
                            this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
                        }
                    }
                }
                // particle just set invisible : scaled to zero and positioned at the origin
                else {
                    this._particle._stillInvisible = true; // mark the particle as invisible
                    for (pt = 0; pt < this._shape.length; pt++) {
                        idx = index + pt * 3;
                        colidx = colorIndex + pt * 4;
                        uvidx = uvIndex + pt * 2;
                        this._positions32[idx] = 0.0;
                        this._positions32[idx + 1] = 0.0;
                        this._positions32[idx + 2] = 0.0;
                        this._normals32[idx] = 0.0;
                        this._normals32[idx + 1] = 0.0;
                        this._normals32[idx + 2] = 0.0;
                        if (this._computeParticleColor && this._particle.color) {
                            this._colors32[colidx] = this._particle.color.r;
                            this._colors32[colidx + 1] = this._particle.color.g;
                            this._colors32[colidx + 2] = this._particle.color.b;
                            this._colors32[colidx + 3] = this._particle.color.a;
                        }
                        if (this._computeParticleTexture) {
                            this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
                            this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
                        }
                    }
                }
                // if the particle intersections must be computed : update the bbInfo
                if (this._particlesIntersect) {
                    var bInfo = this._particle._boundingInfo;
                    var bBox = bInfo.boundingBox;
                    var bSphere = bInfo.boundingSphere;
                    if (!this._bSphereOnly) {
                        // place, scale and rotate the particle bbox within the SPS local system, then update it
                        for (var b = 0; b < bBox.vectors.length; b++) {
                            this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
                            this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
                            this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
                            this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
                            this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
                            this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
                            bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
                            bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
                            bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
                        }
                        bBox._update(this.mesh._worldMatrix);
                    }
                    // place and scale the particle bouding sphere in the SPS local system, then update it
                    this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
                    this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
                    this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
                    this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
                    this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
                    this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
                    bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
                    bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
                    bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
                    bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
                    bSphere._update(this.mesh._worldMatrix);
                }
                // increment indexes for the next particle
                index = idx + 3;
                colorIndex = colidx + 4;
                uvIndex = uvidx + 2;
            }
            // if the VBO must be updated
            if (update) {
                if (this._computeParticleColor) {
                    this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
                }
                if (this._computeParticleTexture) {
                    this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
                }
                this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
                if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
                    if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
                        // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
                        var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
                        BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
                        for (var i = 0; i < this._normals32.length; i++) {
                            this._fixedNormal32[i] = this._normals32[i];
                        }
                    }
                    if (!this.mesh.areNormalsFrozen) {
                        this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
                    }
                }
                if (this._depthSort && this._depthSortParticles) {
                    this.depthSortedParticles.sort(this._depthSortFunction);
                    var dspl = this.depthSortedParticles.length;
                    var sorted = 0;
                    var lind = 0;
                    var sind = 0;
                    var sid = 0;
                    for (sorted = 0; sorted < dspl; sorted++) {
                        lind = this.depthSortedParticles[sorted].indicesLength;
                        sind = this.depthSortedParticles[sorted].ind;
                        for (var i = 0; i < lind; i++) {
                            this._indices32[sid] = this._indices[sind + i];
                            sid++;
                        }
                    }
                    this.mesh.updateIndices(this._indices32);
                }
            }
            if (this._computeBoundingBox) {
                this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
                this.mesh._boundingInfo.update(this.mesh._worldMatrix);
            }
            this.afterUpdateParticles(start, end, update);
            return this;
        };
        SolidParticleSystem.prototype._quaternionRotationYPR = function () {
            this._halfroll = this._roll * 0.5;
            this._halfpitch = this._pitch * 0.5;
            this._halfyaw = this._yaw * 0.5;
            this._sinRoll = Math.sin(this._halfroll);
            this._cosRoll = Math.cos(this._halfroll);
            this._sinPitch = Math.sin(this._halfpitch);
            this._cosPitch = Math.cos(this._halfpitch);
            this._sinYaw = Math.sin(this._halfyaw);
            this._cosYaw = Math.cos(this._halfyaw);
            this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
            this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
            this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
            this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
        };
        SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
            this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
            this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
            this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
            this._rotMatrix.m[3] = 0;
            this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
            this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
            this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
            this._rotMatrix.m[7] = 0;
            this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
            this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
            this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
            this._rotMatrix.m[11] = 0;
            this._rotMatrix.m[12] = 0;
            this._rotMatrix.m[13] = 0;
            this._rotMatrix.m[14] = 0;
            this._rotMatrix.m[15] = 1.0;
        };
        /**
        * Disposes the SPS.
        */
        SolidParticleSystem.prototype.dispose = function () {
            this.mesh.dispose();
            this.vars = null;
            // drop references to internal big arrays for the GC
            this._positions = null;
            this._indices = null;
            this._normals = null;
            this._uvs = null;
            this._colors = null;
            this._indices32 = null;
            this._positions32 = null;
            this._normals32 = null;
            this._fixedNormal32 = null;
            this._uvs32 = null;
            this._colors32 = null;
            this.pickedParticles = null;
        };
        /**
         * Visibilty helper : Recomputes the visible size according to the mesh bounding box
         * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
         * @returns the SPS.
         */
        SolidParticleSystem.prototype.refreshVisibleSize = function () {
            if (!this._isVisibilityBoxLocked) {
                this.mesh.refreshBoundingInfo();
            }
            return this;
        };
        /**
         * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
         * @param size the size (float) of the visibility box
         * note : this doesn't lock the SPS mesh bounding box.
         * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
         */
        SolidParticleSystem.prototype.setVisibilityBox = function (size) {
            var vis = size / 2;
            this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
        };
        Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
            /**
             * Gets whether the SPS as always visible or not
             * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
             */
            get: function () {
                return this._alwaysVisible;
            },
            /**
             * Sets the SPS as always visible or not
             * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
             */
            set: function (val) {
                this._alwaysVisible = val;
                this.mesh.alwaysSelectAsActiveMesh = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
            /**
             * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
             * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
             */
            get: function () {
                return this._isVisibilityBoxLocked;
            },
            /**
             * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
             * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
             */
            set: function (val) {
                this._isVisibilityBoxLocked = val;
                var boundingInfo = this.mesh.getBoundingInfo();
                boundingInfo.isLocked = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
            /**
             * Gets if `setParticles()` computes the particle rotations or not.
             * Default value : true. The SPS is faster when it's set to false.
             * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
             */
            get: function () {
                return this._computeParticleRotation;
            },
            /**
             * Tells to `setParticles()` to compute the particle rotations or not.
             * Default value : true. The SPS is faster when it's set to false.
             * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
             */
            set: function (val) {
                this._computeParticleRotation = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
            /**
             * Gets if `setParticles()` computes the particle colors or not.
             * Default value : true. The SPS is faster when it's set to false.
             * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
             */
            get: function () {
                return this._computeParticleColor;
            },
            /**
             * Tells to `setParticles()` to compute the particle colors or not.
             * Default value : true. The SPS is faster when it's set to false.
             * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
             */
            set: function (val) {
                this._computeParticleColor = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
            /**
             * Gets if `setParticles()` computes the particle textures or not.
             * Default value : true. The SPS is faster when it's set to false.
             * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
             */
            get: function () {
                return this._computeParticleTexture;
            },
            set: function (val) {
                this._computeParticleTexture = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
            /**
             * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
             * Default value : false. The SPS is faster when it's set to false.
             * Note : the particle custom vertex positions aren't stored values.
             */
            get: function () {
                return this._computeParticleVertex;
            },
            /**
             * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
             * Default value : false. The SPS is faster when it's set to false.
             * Note : the particle custom vertex positions aren't stored values.
             */
            set: function (val) {
                this._computeParticleVertex = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
            /**
             * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
             */
            get: function () {
                return this._computeBoundingBox;
            },
            /**
             * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
             */
            set: function (val) {
                this._computeBoundingBox = val;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
            /**
             * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
             * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
             * Default : `true`
             */
            get: function () {
                return this._depthSortParticles;
            },
            /**
             * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
             * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
             * Default : `true`
             */
            set: function (val) {
                this._depthSortParticles = val;
            },
            enumerable: true,
            configurable: true
        });
        // =======================================================================
        // Particle behavior logic
        // these following methods may be overwritten by the user to fit his needs
        /**
         * This function does nothing. It may be overwritten to set all the particle first values.
         * The SPS doesn't call this function, you may have to call it by your own.
         * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
         */
        SolidParticleSystem.prototype.initParticles = function () {
        };
        /**
         * This function does nothing. It may be overwritten to recycle a particle.
         * The SPS doesn't call this function, you may have to call it by your own.
         * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
         * @param particle The particle to recycle
         * @returns the recycled particle
         */
        SolidParticleSystem.prototype.recycleParticle = function (particle) {
            return particle;
        };
        /**
         * Updates a particle : this function should  be overwritten by the user.
         * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
         * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
         * @example : just set a particle position or velocity and recycle conditions
         * @param particle The particle to update
         * @returns the updated particle
         */
        SolidParticleSystem.prototype.updateParticle = function (particle) {
            return particle;
        };
        /**
         * Updates a vertex of a particle : it can be overwritten by the user.
         * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
         * @param particle the current particle
         * @param vertex the current index of the current particle
         * @param pt the index of the current vertex in the particle shape
         * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
         * @example : just set a vertex particle position
         * @returns the updated vertex
         */
        SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
            return vertex;
        };
        /**
         * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
         * This does nothing and may be overwritten by the user.
         * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
         * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
         * @param update the boolean update value actually passed to setParticles()
         */
        SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
        };
        /**
         * This will be called  by `setParticles()` after all the other treatments and just before the actual mesh update.
         * This will be passed three parameters.
         * This does nothing and may be overwritten by the user.
         * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
         * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
         * @param update the boolean update value actually passed to setParticles()
         */
        SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
        };
        return SolidParticleSystem;
    }());
    BABYLON.SolidParticleSystem = SolidParticleSystem;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.solidParticleSystem.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class containing static functions to help procedurally build meshes
     */
    var MeshBuilder = /** @class */ (function () {
        function MeshBuilder() {
        }
        MeshBuilder.updateSideOrientation = function (orientation) {
            if (orientation == BABYLON.Mesh.DOUBLESIDE) {
                return BABYLON.Mesh.DOUBLESIDE;
            }
            if (orientation === undefined || orientation === null) {
                return BABYLON.Mesh.FRONTSIDE;
            }
            return orientation;
        };
        /**
         * Creates a box mesh
         * * The parameter `size` sets the size (float) of each box side (default 1)
         * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
         * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements)
         * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the box mesh
         */
        MeshBuilder.CreateBox = function (name, options, scene) {
            if (scene === void 0) { scene = null; }
            var box = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            box._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateBox(options);
            vertexData.applyToMesh(box, options.updatable);
            return box;
        };
        /**
         * Creates a sphere mesh
         * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
         * * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value of `diameter`)
         * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
         * * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
         * * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude)
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the sphere mesh
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
         */
        MeshBuilder.CreateSphere = function (name, options, scene) {
            var sphere = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            sphere._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateSphere(options);
            vertexData.applyToMesh(sphere, options.updatable);
            return sphere;
        };
        /**
         * Creates a plane polygonal mesh.  By default, this is a disc
         * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
         * * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
         * * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the plane polygonal mesh
         * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
         */
        MeshBuilder.CreateDisc = function (name, options, scene) {
            if (scene === void 0) { scene = null; }
            var disc = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            disc._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateDisc(options);
            vertexData.applyToMesh(disc, options.updatable);
            return disc;
        };
        /**
         * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
         * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
         * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value of `radius`)
         * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
         * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the icosahedron mesh
         * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
         */
        MeshBuilder.CreateIcoSphere = function (name, options, scene) {
            var sphere = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            sphere._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
            vertexData.applyToMesh(sphere, options.updatable);
            return sphere;
        };
        /**
         * Creates a ribbon mesh. The ribbon is a parametric shape.  It has no predefined shape. Its final shape will depend on the input parameters
         * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
         * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
         * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
         * * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path
         * * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11
         * * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
         * * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones
         * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
         * * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that if you set `closePath` to `true`, there's one extra vertex per path in the geometry
         * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the ribbon mesh
         * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
         * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
         */
        MeshBuilder.CreateRibbon = function (name, options, scene) {
            if (scene === void 0) { scene = null; }
            var pathArray = options.pathArray;
            var closeArray = options.closeArray;
            var closePath = options.closePath;
            var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            var instance = options.instance;
            var updatable = options.updatable;
            if (instance) { // existing ribbon instance update
                // positionFunction : ribbon case
                // only pathArray and sideOrientation parameters are taken into account for positions update
                BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
                BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
                var positionFunction = function (positions) {
                    var minlg = pathArray[0].length;
                    var mesh = instance;
                    var i = 0;
                    var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
                    for (var si = 1; si <= ns; si++) {
                        for (var p = 0; p < pathArray.length; p++) {
                            var path = pathArray[p];
                            var l = path.length;
                            minlg = (minlg < l) ? minlg : l;
                            var j = 0;
                            while (j < minlg) {
                                positions[i] = path[j].x;
                                positions[i + 1] = path[j].y;
                                positions[i + 2] = path[j].z;
                                if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
                                    BABYLON.Tmp.Vector3[0].x = path[j].x;
                                }
                                if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
                                    BABYLON.Tmp.Vector3[1].x = path[j].x;
                                }
                                if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
                                    BABYLON.Tmp.Vector3[0].y = path[j].y;
                                }
                                if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
                                    BABYLON.Tmp.Vector3[1].y = path[j].y;
                                }
                                if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
                                    BABYLON.Tmp.Vector3[0].z = path[j].z;
                                }
                                if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
                                    BABYLON.Tmp.Vector3[1].z = path[j].z;
                                }
                                j++;
                                i += 3;
                            }
                            if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
                                positions[i] = path[0].x;
                                positions[i + 1] = path[0].y;
                                positions[i + 2] = path[0].z;
                                i += 3;
                            }
                        }
                    }
                };
                var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                positionFunction(positions);
                instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
                instance._boundingInfo.update(instance._worldMatrix);
                instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
                if (options.colors) {
                    var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
                    for (var c = 0; c < options.colors.length; c++) {
                        colors[c * 4] = options.colors[c].r;
                        colors[c * 4 + 1] = options.colors[c].g;
                        colors[c * 4 + 2] = options.colors[c].b;
                        colors[c * 4 + 3] = options.colors[c].a;
                    }
                    instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
                }
                if (options.uvs) {
                    var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
                    for (var i = 0; i < options.uvs.length; i++) {
                        uvs[i * 2] = options.uvs[i].x;
                        uvs[i * 2 + 1] = options.uvs[i].y;
                    }
                    instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
                }
                if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
                    var indices = instance.getIndices();
                    var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
                    var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
                    BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
                    if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
                        var indexFirst = 0;
                        var indexLast = 0;
                        for (var p = 0; p < pathArray.length; p++) {
                            indexFirst = instance._creationDataStorage.idx[p] * 3;
                            if (p + 1 < pathArray.length) {
                                indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
                            }
                            else {
                                indexLast = normals.length - 3;
                            }
                            normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
                            normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
                            normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
                            normals[indexLast] = normals[indexFirst];
                            normals[indexLast + 1] = normals[indexFirst + 1];
                            normals[indexLast + 2] = normals[indexFirst + 2];
                        }
                    }
                    if (!(instance.areNormalsFrozen)) {
                        instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
                    }
                }
                return instance;
            }
            else { // new ribbon creation
                var ribbon = new BABYLON.Mesh(name, scene);
                ribbon._originalBuilderSideOrientation = sideOrientation;
                ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
                var vertexData = BABYLON.VertexData.CreateRibbon(options);
                if (closePath) {
                    ribbon._creationDataStorage.idx = vertexData._idx;
                }
                ribbon._creationDataStorage.closePath = closePath;
                ribbon._creationDataStorage.closeArray = closeArray;
                vertexData.applyToMesh(ribbon, updatable);
                return ribbon;
            }
        };
        /**
         * Creates a cylinder or a cone mesh
         * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
         * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
         * * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
         * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
         * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
         * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
         * * The parameter `enclose`  (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
         * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
         * * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
         * * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
         * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
         * * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
         * * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
         * * If `enclose` is false, a ring surface is one element.
         * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
         * * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the cylinder mesh
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
         */
        MeshBuilder.CreateCylinder = function (name, options, scene) {
            var cylinder = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            cylinder._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateCylinder(options);
            vertexData.applyToMesh(cylinder, options.updatable);
            return cylinder;
        };
        /**
         * Creates a torus mesh
         * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
         * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
         * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the torus mesh
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
         */
        MeshBuilder.CreateTorus = function (name, options, scene) {
            var torus = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            torus._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateTorus(options);
            vertexData.applyToMesh(torus, options.updatable);
            return torus;
        };
        /**
         * Creates a torus knot mesh
         * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
         * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
         * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
         * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the torus knot mesh
         * @see  http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
         */
        MeshBuilder.CreateTorusKnot = function (name, options, scene) {
            var torusKnot = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            torusKnot._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
            vertexData.applyToMesh(torusKnot, options.updatable);
            return torusKnot;
        };
        /**
         * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
         * * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter
         * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
         * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
         * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
         * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
         * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
         * * Updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
         * @param name defines the name of the new line system
         * @param options defines the options used to create the line system
         * @param scene defines the hosting scene
         * @returns a new line system mesh
         */
        MeshBuilder.CreateLineSystem = function (name, options, scene) {
            var instance = options.instance;
            var lines = options.lines;
            var colors = options.colors;
            if (instance) { // lines update
                var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
                var vertexColor;
                var lineColors;
                if (colors) {
                    vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
                }
                var i = 0;
                var c = 0;
                for (var l = 0; l < lines.length; l++) {
                    var points = lines[l];
                    for (var p = 0; p < points.length; p++) {
                        positions[i] = points[p].x;
                        positions[i + 1] = points[p].y;
                        positions[i + 2] = points[p].z;
                        if (colors && vertexColor) {
                            lineColors = colors[l];
                            vertexColor[c] = lineColors[p].r;
                            vertexColor[c + 1] = lineColors[p].g;
                            vertexColor[c + 2] = lineColors[p].b;
                            vertexColor[c + 3] = lineColors[p].a;
                            c += 4;
                        }
                        i += 3;
                    }
                }
                instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
                if (colors && vertexColor) {
                    instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
                }
                return instance;
            }
            // line system creation
            var useVertexColor = (colors) ? true : false;
            var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
            var vertexData = BABYLON.VertexData.CreateLineSystem(options);
            vertexData.applyToMesh(lineSystem, options.updatable);
            return lineSystem;
        };
        /**
         * Creates a line mesh
         * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
         * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
         * * The parameter `points` is an array successive Vector3
         * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * * The optional parameter `colors` is an array of successive Color4, one per line point
         * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
         * * When updating an instance, remember that only point positions can change, not the number of points
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
         * @param name defines the name of the new line system
         * @param options defines the options used to create the line system
         * @param scene defines the hosting scene
         * @returns a new line mesh
         */
        MeshBuilder.CreateLines = function (name, options, scene) {
            if (scene === void 0) { scene = null; }
            var colors = (options.colors) ? [options.colors] : null;
            var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
            return lines;
        };
        /**
         * Creates a dashed line mesh
         * * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter
         * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
         * * The parameter `points` is an array successive Vector3
         * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
         * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
         * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
         * * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
         * * When updating an instance, remember that only point positions can change, not the number of points
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the dashed line mesh
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
         */
        MeshBuilder.CreateDashedLines = function (name, options, scene) {
            if (scene === void 0) { scene = null; }
            var points = options.points;
            var instance = options.instance;
            var gapSize = options.gapSize || 1;
            var dashSize = options.dashSize || 3;
            if (instance) { //  dashed lines update
                var positionFunction = function (positions) {
                    var curvect = BABYLON.Vector3.Zero();
                    var nbSeg = positions.length / 6;
                    var lg = 0;
                    var nb = 0;
                    var shft = 0;
                    var dashshft = 0;
                    var curshft = 0;
                    var p = 0;
                    var i = 0;
                    var j = 0;
                    for (i = 0; i < points.length - 1; i++) {
                        points[i + 1].subtractToRef(points[i], curvect);
                        lg += curvect.length();
                    }
                    shft = lg / nbSeg;
                    var dashSize = instance._creationDataStorage.dashSize;
                    var gapSize = instance._creationDataStorage.gapSize;
                    dashshft = dashSize * shft / (dashSize + gapSize);
                    for (i = 0; i < points.length - 1; i++) {
                        points[i + 1].subtractToRef(points[i], curvect);
                        nb = Math.floor(curvect.length() / shft);
                        curvect.normalize();
                        j = 0;
                        while (j < nb && p < positions.length) {
                            curshft = shft * j;
                            positions[p] = points[i].x + curshft * curvect.x;
                            positions[p + 1] = points[i].y + curshft * curvect.y;
                            positions[p + 2] = points[i].z + curshft * curvect.z;
                            positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
                            positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
                            positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
                            p += 6;
                            j++;
                        }
                    }
                    while (p < positions.length) {
                        positions[p] = points[i].x;
                        positions[p + 1] = points[i].y;
                        positions[p + 2] = points[i].z;
                        p += 3;
                    }
                };
                instance.updateMeshPositions(positionFunction, false);
                return instance;
            }
            // dashed lines creation
            var dashedLines = new BABYLON.LinesMesh(name, scene);
            var vertexData = BABYLON.VertexData.CreateDashedLines(options);
            vertexData.applyToMesh(dashedLines, options.updatable);
            dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
            dashedLines._creationDataStorage.dashSize = dashSize;
            dashedLines._creationDataStorage.gapSize = gapSize;
            return dashedLines;
        };
        /**
         * Creates an extruded shape mesh. The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
         * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
         * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
         * * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
         * * The parameter `scale` (float, default 1) is the value to scale the shape.
         * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
         * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the extruded shape mesh
         * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
         */
        MeshBuilder.ExtrudeShape = function (name, options, scene) {
            if (scene === void 0) { scene = null; }
            var path = options.path;
            var shape = options.shape;
            var scale = options.scale || 1;
            var rotation = options.rotation || 0;
            var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
            var updatable = options.updatable;
            var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            var instance = options.instance || null;
            var invertUV = options.invertUV || false;
            return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable ? true : false, sideOrientation, instance, invertUV, options.frontUVs || null, options.backUVs || null);
        };
        /**
         * Creates an custom extruded shape mesh.
         * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
         * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis.
         * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
         * * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
         * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
         * * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path and the distance of this point from the begining of the path
         * * It must returns a float value that will be the scale value applied to the shape on each path point
         * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
         * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
         * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
         * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the custom extruded shape mesh
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
         * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
         */
        MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
            var path = options.path;
            var shape = options.shape;
            var scaleFunction = options.scaleFunction || (function () { return 1; });
            var rotationFunction = options.rotationFunction || (function () { return 0; });
            var ribbonCloseArray = options.ribbonCloseArray || false;
            var ribbonClosePath = options.ribbonClosePath || false;
            var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
            var updatable = options.updatable;
            var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            var instance = options.instance;
            var invertUV = options.invertUV || false;
            return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable ? true : false, sideOrientation, instance || null, invertUV, options.frontUVs || null, options.backUVs || null);
        };
        /**
         * Creates lathe mesh.
         * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
         * * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
         * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
         * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
     * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
         * * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape
         * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
         * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the lathe mesh
         * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
         */
        MeshBuilder.CreateLathe = function (name, options, scene) {
            var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
            var closed = (options.closed === undefined) ? true : options.closed;
            var shape = options.shape;
            var radius = options.radius || 1;
            var tessellation = options.tessellation || 64;
            var clip = options.clip || 0;
            var updatable = options.updatable;
            var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            var cap = options.cap || BABYLON.Mesh.NO_CAP;
            var pi2 = Math.PI * 2;
            var paths = new Array();
            var invertUV = options.invertUV || false;
            var i = 0;
            var p = 0;
            var step = pi2 / tessellation * arc;
            var rotated;
            var path = new Array();
            for (i = 0; i <= tessellation - clip; i++) {
                var path = [];
                if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
                    path.push(new BABYLON.Vector3(0, shape[0].y, 0));
                    path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
                }
                for (p = 0; p < shape.length; p++) {
                    rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
                    path.push(rotated);
                }
                if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
                    path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[shape.length - 1].x * radius, shape[shape.length - 1].y, Math.sin(i * step) * shape[shape.length - 1].x * radius));
                    path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
                }
                paths.push(path);
            }
            // lathe ribbon
            var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
            return lathe;
        };
        /**
         * Creates a plane mesh
         * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
         * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
         * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the plane mesh
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
         */
        MeshBuilder.CreatePlane = function (name, options, scene) {
            var plane = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            plane._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreatePlane(options);
            vertexData.applyToMesh(plane, options.updatable);
            if (options.sourcePlane) {
                plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
                var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
                var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
                if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
                    plane.rotate(vectorProduct, product);
                }
            }
            return plane;
        };
        /**
         * Creates a ground mesh
         * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
         * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the ground mesh
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
         */
        MeshBuilder.CreateGround = function (name, options, scene) {
            var ground = new BABYLON.GroundMesh(name, scene);
            ground._setReady(false);
            ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
            ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
            ground._width = options.width || 1;
            ground._height = options.height || 1;
            ground._maxX = ground._width / 2;
            ground._maxZ = ground._height / 2;
            ground._minX = -ground._maxX;
            ground._minZ = -ground._maxZ;
            var vertexData = BABYLON.VertexData.CreateGround(options);
            vertexData.applyToMesh(ground, options.updatable);
            ground._setReady(true);
            return ground;
        };
        /**
         * Creates a tiled ground mesh
         * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
         * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
         * * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
         * * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the tiled ground mesh
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
         */
        MeshBuilder.CreateTiledGround = function (name, options, scene) {
            var tiledGround = new BABYLON.Mesh(name, scene);
            var vertexData = BABYLON.VertexData.CreateTiledGround(options);
            vertexData.applyToMesh(tiledGround, options.updatable);
            return tiledGround;
        };
        /**
         * Creates a ground mesh from a height map
         * * The parameter `url` sets the URL of the height map image resource.
         * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
         * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
         * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
         * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
         * * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
         * * The parameter `onReady` is a javascript callback function that will be called  once the mesh is just built (the height map download can last some time).
         * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
         * @param name defines the name of the mesh
         * @param url defines the url to the height map
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the ground mesh
         * @see http://doc.babylonjs.com/babylon101/height_map
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
         */
        MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
            var width = options.width || 10.0;
            var height = options.height || 10.0;
            var subdivisions = options.subdivisions || 1 | 0;
            var minHeight = options.minHeight || 0.0;
            var maxHeight = options.maxHeight || 1.0;
            var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
            var alphaFilter = options.alphaFilter || 0.0;
            var updatable = options.updatable;
            var onReady = options.onReady;
            var ground = new BABYLON.GroundMesh(name, scene);
            ground._subdivisionsX = subdivisions;
            ground._subdivisionsY = subdivisions;
            ground._width = width;
            ground._height = height;
            ground._maxX = ground._width / 2.0;
            ground._maxZ = ground._height / 2.0;
            ground._minX = -ground._maxX;
            ground._minZ = -ground._maxZ;
            ground._setReady(false);
            var onload = function (img) {
                // Getting height map data
                var canvas = document.createElement("canvas");
                var context = canvas.getContext("2d");
                if (!context) {
                    throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
                }
                if (scene.isDisposed) {
                    return;
                }
                var bufferWidth = img.width;
                var bufferHeight = img.height;
                canvas.width = bufferWidth;
                canvas.height = bufferHeight;
                context.drawImage(img, 0, 0);
                // Create VertexData from map data
                // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
                var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
                var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
                    width: width, height: height,
                    subdivisions: subdivisions,
                    minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
                    buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
                    alphaFilter: alphaFilter
                });
                vertexData.applyToMesh(ground, updatable);
                //execute ready callback, if set
                if (onReady) {
                    onReady(ground);
                }
                ground._setReady(true);
            };
            BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
            return ground;
        };
        /**
         * Creates a polygon mesh
         * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
         * * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
         * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4)
         * * Remember you can only change the shape positions, not their number when updating a polygon
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the polygon mesh
         */
        MeshBuilder.CreatePolygon = function (name, options, scene) {
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            var shape = options.shape;
            var holes = options.holes || [];
            var depth = options.depth || 0;
            var contours = [];
            var hole = [];
            for (var i = 0; i < shape.length; i++) {
                contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
            }
            var epsilon = 0.00000001;
            if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
                contours.pop();
            }
            var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
            for (var hNb = 0; hNb < holes.length; hNb++) {
                hole = [];
                for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
                    hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
                }
                polygonTriangulation.addHole(hole);
            }
            var polygon = polygonTriangulation.build(options.updatable, depth);
            polygon._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
            vertexData.applyToMesh(polygon, options.updatable);
            return polygon;
        };
        /**
         * Creates an extruded polygon mesh, with depth in the Y direction.
         * * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements)
         * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the polygon mesh
         */
        MeshBuilder.ExtrudePolygon = function (name, options, scene) {
            return MeshBuilder.CreatePolygon(name, options, scene);
        };
        /**
         * Creates a tube mesh.
         * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
         * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
         * * The parameter `radius` (positive float, default 1) sets the tube radius size
         * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
         * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
         * * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path. It must return a radius value (positive float)
         * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
         * * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
         * * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the tube mesh
         * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
         * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
         */
        MeshBuilder.CreateTube = function (name, options, scene) {
            var path = options.path;
            var instance = options.instance;
            var radius = 1.0;
            if (options.radius !== undefined) {
                radius = options.radius;
            }
            else if (instance) {
                radius = instance._creationDataStorage.radius;
            }
            var tessellation = options.tessellation || 64 | 0;
            var radiusFunction = options.radiusFunction || null;
            var cap = options.cap || BABYLON.Mesh.NO_CAP;
            var invertUV = options.invertUV || false;
            var updatable = options.updatable;
            var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
            // tube geometry
            var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
                var tangents = path3D.getTangents();
                var normals = path3D.getNormals();
                var distances = path3D.getDistances();
                var pi2 = Math.PI * 2;
                var step = pi2 / tessellation * arc;
                var returnRadius = function () { return radius; };
                var radiusFunctionFinal = radiusFunction || returnRadius;
                var circlePath;
                var rad;
                var normal;
                var rotated;
                var rotationMatrix = BABYLON.Tmp.Matrix[0];
                var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
                for (var i = 0; i < path.length; i++) {
                    rad = radiusFunctionFinal(i, distances[i]); // current radius
                    circlePath = Array(); // current circle array
                    normal = normals[i]; // current normal
                    for (var t = 0; t < tessellation; t++) {
                        BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
                        rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
                        BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
                        rotated.scaleInPlace(rad).addInPlace(path[i]);
                        circlePath[t] = rotated;
                    }
                    circlePaths[index] = circlePath;
                    index++;
                }
                // cap
                var capPath = function (nbPoints, pathIndex) {
                    var pointCap = Array();
                    for (var i = 0; i < nbPoints; i++) {
                        pointCap.push(path[pathIndex]);
                    }
                    return pointCap;
                };
                switch (cap) {
                    case BABYLON.Mesh.NO_CAP:
                        break;
                    case BABYLON.Mesh.CAP_START:
                        circlePaths[0] = capPath(tessellation, 0);
                        circlePaths[1] = circlePaths[2].slice(0);
                        break;
                    case BABYLON.Mesh.CAP_END:
                        circlePaths[index] = circlePaths[index - 1].slice(0);
                        circlePaths[index + 1] = capPath(tessellation, path.length - 1);
                        break;
                    case BABYLON.Mesh.CAP_ALL:
                        circlePaths[0] = capPath(tessellation, 0);
                        circlePaths[1] = circlePaths[2].slice(0);
                        circlePaths[index] = circlePaths[index - 1].slice(0);
                        circlePaths[index + 1] = capPath(tessellation, path.length - 1);
                        break;
                    default:
                        break;
                }
                return circlePaths;
            };
            var path3D;
            var pathArray;
            if (instance) { // tube update
                var storage = instance._creationDataStorage;
                var arc = options.arc || storage.arc;
                path3D = storage.path3D.update(path);
                pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
                instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
                // Update mode, no need to recreate the storage.
                storage.path3D = path3D;
                storage.pathArray = pathArray;
                storage.arc = arc;
                storage.radius = radius;
                return instance;
            }
            // tube creation
            path3D = new BABYLON.Path3D(path);
            var newPathArray = new Array();
            cap = (cap < 0 || cap > 3) ? 0 : cap;
            pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
            var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
            tube._creationDataStorage.pathArray = pathArray;
            tube._creationDataStorage.path3D = path3D;
            tube._creationDataStorage.tessellation = tessellation;
            tube._creationDataStorage.cap = cap;
            tube._creationDataStorage.arc = options.arc;
            tube._creationDataStorage.radius = radius;
            return tube;
        };
        /**
         * Creates a polyhedron mesh
         * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
         * * The parameter `size` (positive float, default 1) sets the polygon size
         * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
         * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
         * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
         * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
         * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
         * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
         * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
         * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
         * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
         * @param name defines the name of the mesh
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the polyhedron mesh
         * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
         */
        MeshBuilder.CreatePolyhedron = function (name, options, scene) {
            var polyhedron = new BABYLON.Mesh(name, scene);
            options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
            polyhedron._originalBuilderSideOrientation = options.sideOrientation;
            var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
            vertexData.applyToMesh(polyhedron, options.updatable);
            return polyhedron;
        };
        /**
         * Creates a decal mesh.
         * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal
         * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
         * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
         * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
         * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
         * @param name defines the name of the mesh
         * @param sourceMesh defines the mesh where the decal must be applied
         * @param options defines the options used to create the mesh
         * @param scene defines the hosting scene
         * @returns the decal mesh
         * @see http://doc.babylonjs.com/how_to/decals
         */
        MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
            var indices = sourceMesh.getIndices();
            var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var position = options.position || BABYLON.Vector3.Zero();
            var normal = options.normal || BABYLON.Vector3.Up();
            var size = options.size || BABYLON.Vector3.One();
            var angle = options.angle || 0;
            // Getting correct rotation
            if (!normal) {
                var target = new BABYLON.Vector3(0, 0, 1);
                var camera = sourceMesh.getScene().activeCamera;
                var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
                normal = camera.globalPosition.subtract(cameraWorldTarget);
            }
            var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
            var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
            var pitch = Math.atan2(normal.y, len);
            // Matrix
            var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
            var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
            var meshWorldMatrix = sourceMesh.getWorldMatrix();
            var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
            var vertexData = new BABYLON.VertexData();
            vertexData.indices = [];
            vertexData.positions = [];
            vertexData.normals = [];
            vertexData.uvs = [];
            var currentVertexDataIndex = 0;
            var extractDecalVector3 = function (indexId) {
                var result = new BABYLON.PositionNormalVertex();
                if (!indices || !positions || !normals) {
                    return result;
                }
                var vertexId = indices[indexId];
                result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
                // Send vector to decal local world
                result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
                // Get normal
                result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
                result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
                return result;
            }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
            var clip = function (vertices, axis) {
                if (vertices.length === 0) {
                    return vertices;
                }
                var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
                var clipVertices = function (v0, v1) {
                    var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
                    return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
                };
                var result = new Array();
                for (var index = 0; index < vertices.length; index += 3) {
                    var v1Out;
                    var v2Out;
                    var v3Out;
                    var total = 0;
                    var nV1 = null;
                    var nV2 = null;
                    var nV3 = null;
                    var nV4 = null;
                    var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
                    var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
                    var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
                    v1Out = d1 > 0;
                    v2Out = d2 > 0;
                    v3Out = d3 > 0;
                    total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
                    switch (total) {
                        case 0:
                            result.push(vertices[index]);
                            result.push(vertices[index + 1]);
                            result.push(vertices[index + 2]);
                            break;
                        case 1:
                            if (v1Out) {
                                nV1 = vertices[index + 1];
                                nV2 = vertices[index + 2];
                                nV3 = clipVertices(vertices[index], nV1);
                                nV4 = clipVertices(vertices[index], nV2);
                            }
                            if (v2Out) {
                                nV1 = vertices[index];
                                nV2 = vertices[index + 2];
                                nV3 = clipVertices(vertices[index + 1], nV1);
                                nV4 = clipVertices(vertices[index + 1], nV2);
                                result.push(nV3);
                                result.push(nV2.clone());
                                result.push(nV1.clone());
                                result.push(nV2.clone());
                                result.push(nV3.clone());
                                result.push(nV4);
                                break;
                            }
                            if (v3Out) {
                                nV1 = vertices[index];
                                nV2 = vertices[index + 1];
                                nV3 = clipVertices(vertices[index + 2], nV1);
                                nV4 = clipVertices(vertices[index + 2], nV2);
                            }
                            if (nV1 && nV2 && nV3 && nV4) {
                                result.push(nV1.clone());
                                result.push(nV2.clone());
                                result.push(nV3);
                                result.push(nV4);
                                result.push(nV3.clone());
                                result.push(nV2.clone());
                            }
                            break;
                        case 2:
                            if (!v1Out) {
                                nV1 = vertices[index].clone();
                                nV2 = clipVertices(nV1, vertices[index + 1]);
                                nV3 = clipVertices(nV1, vertices[index + 2]);
                                result.push(nV1);
                                result.push(nV2);
                                result.push(nV3);
                            }
                            if (!v2Out) {
                                nV1 = vertices[index + 1].clone();
                                nV2 = clipVertices(nV1, vertices[index + 2]);
                                nV3 = clipVertices(nV1, vertices[index]);
                                result.push(nV1);
                                result.push(nV2);
                                result.push(nV3);
                            }
                            if (!v3Out) {
                                nV1 = vertices[index + 2].clone();
                                nV2 = clipVertices(nV1, vertices[index]);
                                nV3 = clipVertices(nV1, vertices[index + 1]);
                                result.push(nV1);
                                result.push(nV2);
                                result.push(nV3);
                            }
                            break;
                        case 3:
                            break;
                    }
                }
                return result;
            };
            for (var index = 0; index < indices.length; index += 3) {
                var faceVertices = new Array();
                faceVertices.push(extractDecalVector3(index));
                faceVertices.push(extractDecalVector3(index + 1));
                faceVertices.push(extractDecalVector3(index + 2));
                // Clip
                faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
                faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
                if (faceVertices.length === 0) {
                    continue;
                }
                // Add UVs and get back to world
                for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
                    var vertex = faceVertices[vIndex];
                    //TODO check for Int32Array | Uint32Array | Uint16Array
                    vertexData.indices.push(currentVertexDataIndex);
                    vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
                    vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
                    vertexData.uvs.push(0.5 + vertex.position.x / size.x);
                    vertexData.uvs.push(0.5 + vertex.position.y / size.y);
                    currentVertexDataIndex++;
                }
            }
            // Return mesh
            var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
            vertexData.applyToMesh(decal);
            decal.position = position.clone();
            decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
            return decal;
        };
        // Privates
        MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
            // extrusion geometry
            var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
                var tangents = path3D.getTangents();
                var normals = path3D.getNormals();
                var binormals = path3D.getBinormals();
                var distances = path3D.getDistances();
                var angle = 0;
                var returnScale = function () { return scale !== null ? scale : 1; };
                var returnRotation = function () { return rotation !== null ? rotation : 0; };
                var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
                var scl = custom && scaleFunction ? scaleFunction : returnScale;
                var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
                var rotationMatrix = BABYLON.Tmp.Matrix[0];
                for (var i = 0; i < curve.length; i++) {
                    var shapePath = new Array();
                    var angleStep = rotate(i, distances[i]);
                    var scaleRatio = scl(i, distances[i]);
                    for (var p = 0; p < shape.length; p++) {
                        BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
                        var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
                        var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
                        BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
                        rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
                        shapePath[p] = rotated;
                    }
                    shapePaths[index] = shapePath;
                    angle += angleStep;
                    index++;
                }
                // cap
                var capPath = function (shapePath) {
                    var pointCap = Array();
                    var barycenter = BABYLON.Vector3.Zero();
                    var i;
                    for (i = 0; i < shapePath.length; i++) {
                        barycenter.addInPlace(shapePath[i]);
                    }
                    barycenter.scaleInPlace(1.0 / shapePath.length);
                    for (i = 0; i < shapePath.length; i++) {
                        pointCap.push(barycenter);
                    }
                    return pointCap;
                };
                switch (cap) {
                    case BABYLON.Mesh.NO_CAP:
                        break;
                    case BABYLON.Mesh.CAP_START:
                        shapePaths[0] = capPath(shapePaths[2]);
                        shapePaths[1] = shapePaths[2];
                        break;
                    case BABYLON.Mesh.CAP_END:
                        shapePaths[index] = shapePaths[index - 1];
                        shapePaths[index + 1] = capPath(shapePaths[index - 1]);
                        break;
                    case BABYLON.Mesh.CAP_ALL:
                        shapePaths[0] = capPath(shapePaths[2]);
                        shapePaths[1] = shapePaths[2];
                        shapePaths[index] = shapePaths[index - 1];
                        shapePaths[index + 1] = capPath(shapePaths[index - 1]);
                        break;
                    default:
                        break;
                }
                return shapePaths;
            };
            var path3D;
            var pathArray;
            if (instance) { // instance update
                var storage = instance._creationDataStorage;
                path3D = storage.path3D.update(curve);
                pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
                instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
                return instance;
            }
            // extruded shape creation
            path3D = new BABYLON.Path3D(curve);
            var newShapePaths = new Array();
            cap = (cap < 0 || cap > 3) ? 0 : cap;
            pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
            var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
            extrudedGeneric._creationDataStorage.pathArray = pathArray;
            extrudedGeneric._creationDataStorage.path3D = path3D;
            extrudedGeneric._creationDataStorage.cap = cap;
            return extrudedGeneric;
        };
        return MeshBuilder;
    }());
    BABYLON.MeshBuilder = MeshBuilder;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.meshBuilder.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Draco compression (https://google.github.io/draco/)
     *
     * This class wraps the Draco module.
     *
     * **Encoder**
     *
     * The encoder is not currently implemented.
     *
     * **Decoder**
     *
     * By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
     *
     * To update the configuration, use the following code:
     * ```javascript
     *     BABYLON.DracoCompression.Configuration = {
     *         decoder: {
     *             wasmUrl: "<url to the WebAssembly library>",
     *             wasmBinaryUrl: "<url to the WebAssembly binary>",
     *             fallbackUrl: "<url to the fallback JavaScript library>",
     *         }
     *     };
     * ```
     *
     * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
     * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
     * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
     *
     * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
     * ```javascript
     *     var dracoCompression = new BABYLON.DracoCompression();
     *     var vertexData = await dracoCompression.decodeMeshAsync(data, {
     *         [BABYLON.VertexBuffer.PositionKind]: 0
     *     });
     * ```
     *
     * @see https://www.babylonjs-playground.com/#N3EK4B#0
     */
    var DracoCompression = /** @class */ (function () {
        /**
         * Constructor
         */
        function DracoCompression() {
        }
        Object.defineProperty(DracoCompression, "DecoderAvailable", {
            /**
             * Returns true if the decoder is available.
             */
            get: function () {
                if (typeof DracoDecoderModule !== "undefined") {
                    return true;
                }
                var decoder = DracoCompression.Configuration.decoder;
                if (decoder) {
                    if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
                        return true;
                    }
                    if (decoder.fallbackUrl) {
                        return true;
                    }
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Stop all async operations and release resources.
         */
        DracoCompression.prototype.dispose = function () {
        };
        /**
         * Decode Draco compressed mesh data to vertex data.
         * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
         * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
         * @returns A promise that resolves with the decoded vertex data
         */
        DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
            var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
            return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
                var module = wrappedModule.module;
                var vertexData = new BABYLON.VertexData();
                var buffer = new module.DecoderBuffer();
                buffer.Init(dataView, dataView.byteLength);
                var decoder = new module.Decoder();
                var geometry;
                var status;
                try {
                    var type = decoder.GetEncodedGeometryType(buffer);
                    switch (type) {
                        case module.TRIANGULAR_MESH:
                            geometry = new module.Mesh();
                            status = decoder.DecodeBufferToMesh(buffer, geometry);
                            break;
                        case module.POINT_CLOUD:
                            geometry = new module.PointCloud();
                            status = decoder.DecodeBufferToPointCloud(buffer, geometry);
                            break;
                        default:
                            throw new Error("Invalid geometry type " + type);
                    }
                    if (!status.ok() || !geometry.ptr) {
                        throw new Error(status.error_msg());
                    }
                    var numPoints = geometry.num_points();
                    if (type === module.TRIANGULAR_MESH) {
                        var numFaces = geometry.num_faces();
                        var faceIndices = new module.DracoInt32Array();
                        try {
                            var indices = new Uint32Array(numFaces * 3);
                            for (var i = 0; i < numFaces; i++) {
                                decoder.GetFaceFromMesh(geometry, i, faceIndices);
                                var offset = i * 3;
                                indices[offset + 0] = faceIndices.GetValue(0);
                                indices[offset + 1] = faceIndices.GetValue(1);
                                indices[offset + 2] = faceIndices.GetValue(2);
                            }
                            vertexData.indices = indices;
                        }
                        finally {
                            module.destroy(faceIndices);
                        }
                    }
                    for (var kind in attributes) {
                        var uniqueId = attributes[kind];
                        var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
                        var dracoData = new module.DracoFloat32Array();
                        try {
                            decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
                            var babylonData = new Float32Array(numPoints * attribute.num_components());
                            for (var i = 0; i < babylonData.length; i++) {
                                babylonData[i] = dracoData.GetValue(i);
                            }
                            vertexData.set(babylonData, kind);
                        }
                        finally {
                            module.destroy(dracoData);
                        }
                    }
                }
                finally {
                    if (geometry) {
                        module.destroy(geometry);
                    }
                    module.destroy(decoder);
                    module.destroy(buffer);
                }
                return vertexData;
            });
        };
        DracoCompression._GetDecoderModule = function () {
            if (!DracoCompression._DecoderModulePromise) {
                var promise = null;
                var config_1 = {};
                if (typeof DracoDecoderModule !== "undefined") {
                    promise = Promise.resolve();
                }
                else {
                    var decoder = DracoCompression.Configuration.decoder;
                    if (decoder) {
                        if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
                            promise = Promise.all([
                                DracoCompression._LoadScriptAsync(decoder.wasmUrl),
                                DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
                                    config_1.wasmBinary = data;
                                })
                            ]);
                        }
                        else if (decoder.fallbackUrl) {
                            promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
                        }
                    }
                }
                if (!promise) {
                    throw new Error("Draco decoder module is not available");
                }
                DracoCompression._DecoderModulePromise = promise.then(function () {
                    return new Promise(function (resolve) {
                        config_1.onModuleLoaded = function (decoderModule) {
                            // decoderModule is Promise-like. Wrap before resolving to avoid loop.
                            resolve({ module: decoderModule });
                        };
                        DracoDecoderModule(config_1);
                    });
                });
            }
            return DracoCompression._DecoderModulePromise;
        };
        DracoCompression._LoadScriptAsync = function (url) {
            return new Promise(function (resolve, reject) {
                BABYLON.Tools.LoadScript(url, function () {
                    resolve();
                }, function (message) {
                    reject(new Error(message));
                });
            });
        };
        DracoCompression._LoadFileAsync = function (url) {
            return new Promise(function (resolve, reject) {
                BABYLON.Tools.LoadFile(url, function (data) {
                    resolve(data);
                }, undefined, undefined, true, function (request, exception) {
                    reject(exception);
                });
            });
        };
        /**
         * The configuration. Defaults to the following urls:
         * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
         * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
         * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
         */
        DracoCompression.Configuration = {
            decoder: {
                wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
                wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
                fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
            }
        };
        return DracoCompression;
    }());
    BABYLON.DracoCompression = DracoCompression;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.dracoCompression.js.map

var BABYLON;
(function (BABYLON) {
    // Sets the default audio engine to Babylon JS.
    BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
    /**
     * This represents the default audio engine used in babylon.
     * It is responsible to play, synchronize and analyse sounds throughout the  application.
     * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
     */
    var AudioEngine = /** @class */ (function () {
        /**
         * Instantiates a new audio engine.
         *
         * There should be only one per page as some browsers restrict the number
         * of audio contexts you can create.
         * @param hostElement defines the host element where to display the mute icon if necessary
         */
        function AudioEngine(hostElement) {
            if (hostElement === void 0) { hostElement = null; }
            var _this = this;
            this._audioContext = null;
            this._audioContextInitialized = false;
            this._muteButton = null;
            /**
             * Gets whether the current host supports Web Audio and thus could create AudioContexts.
             */
            this.canUseWebAudio = false;
            /**
             * Defines if Babylon should emit a warning if WebAudio is not supported.
             * @ignoreNaming
             */
            this.WarnedWebAudioUnsupported = false;
            /**
             * Gets whether or not mp3 are supported by your browser.
             */
            this.isMP3supported = false;
            /**
             * Gets whether or not ogg are supported by your browser.
             */
            this.isOGGsupported = false;
            /**
             * Gets whether audio has been unlocked on the device.
             * Some Browsers have strong restrictions about Audio and won t autoplay unless
             * a user interaction has happened.
             */
            this.unlocked = true;
            /**
             * Defines if the audio engine relies on a custom unlocked button.
             * In this case, the embedded button will not be displayed.
             */
            this.useCustomUnlockedButton = false;
            /**
             * Event raised when audio has been unlocked on the browser.
             */
            this.onAudioUnlockedObservable = new BABYLON.Observable();
            /**
             * Event raised when audio has been locked on the browser.
             */
            this.onAudioLockedObservable = new BABYLON.Observable();
            this._tryToRun = false;
            this._onResize = function () {
                _this._moveButtonToTopLeft();
            };
            if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
                window.AudioContext = window.AudioContext || window.webkitAudioContext;
                this.canUseWebAudio = true;
            }
            var audioElem = document.createElement('audio');
            this._hostElement = hostElement;
            try {
                if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
                    this.isMP3supported = true;
                }
            }
            catch (e) {
                // protect error during capability check.
            }
            try {
                if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
                    this.isOGGsupported = true;
                }
            }
            catch (e) {
                // protect error during capability check.
            }
        }
        Object.defineProperty(AudioEngine.prototype, "audioContext", {
            /**
             * Gets the current AudioContext if available.
             */
            get: function () {
                if (!this._audioContextInitialized) {
                    this._initializeAudioContext();
                }
                else {
                    if (!this.unlocked && !this._muteButton) {
                        this._displayMuteButton();
                    }
                }
                return this._audioContext;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Flags the audio engine in Locked state.
         * This happens due to new browser policies preventing audio to autoplay.
         */
        AudioEngine.prototype.lock = function () {
            this._triggerSuspendedState();
        };
        /**
         * Unlocks the audio engine once a user action has been done on the dom.
         * This is helpful to resume play once browser policies have been satisfied.
         */
        AudioEngine.prototype.unlock = function () {
            this._triggerRunningState();
        };
        AudioEngine.prototype._resumeAudioContext = function () {
            var result;
            if (this._audioContext.resume) {
                result = this._audioContext.resume();
            }
            return result || Promise.resolve();
        };
        AudioEngine.prototype._initializeAudioContext = function () {
            try {
                if (this.canUseWebAudio) {
                    this._audioContext = new AudioContext();
                    // create a global volume gain node
                    this.masterGain = this._audioContext.createGain();
                    this.masterGain.gain.value = 1;
                    this.masterGain.connect(this._audioContext.destination);
                    this._audioContextInitialized = true;
                    if (this._audioContext.state === "running") {
                        // Do not wait for the promise to unlock.
                        this._triggerRunningState();
                    }
                }
            }
            catch (e) {
                this.canUseWebAudio = false;
                BABYLON.Tools.Error("Web Audio: " + e.message);
            }
        };
        AudioEngine.prototype._triggerRunningState = function () {
            var _this = this;
            if (this._tryToRun) {
                return;
            }
            this._tryToRun = true;
            this._resumeAudioContext()
                .then(function () {
                _this._tryToRun = false;
                if (_this._muteButton) {
                    _this._hideMuteButton();
                }
            }).catch(function () {
                _this._tryToRun = false;
                _this.unlocked = false;
            });
            // Notify users that the audio stack is unlocked/unmuted
            this.unlocked = true;
            this.onAudioUnlockedObservable.notifyObservers(this);
        };
        AudioEngine.prototype._triggerSuspendedState = function () {
            this.unlocked = false;
            this.onAudioLockedObservable.notifyObservers(this);
            this._displayMuteButton();
        };
        AudioEngine.prototype._displayMuteButton = function () {
            var _this = this;
            if (this.useCustomUnlockedButton) {
                return;
            }
            this._muteButton = document.createElement("BUTTON");
            this._muteButton.className = "babylonUnmuteIcon";
            this._muteButton.id = "babylonUnmuteIconBtn";
            this._muteButton.title = "Unmute";
            var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E);  background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }";
            var style = document.createElement('style');
            style.appendChild(document.createTextNode(css));
            document.getElementsByTagName('head')[0].appendChild(style);
            document.body.appendChild(this._muteButton);
            this._moveButtonToTopLeft();
            this._muteButton.addEventListener('touchend', function () {
                _this._triggerRunningState();
            }, true);
            this._muteButton.addEventListener('click', function () {
                _this._triggerRunningState();
            }, true);
            window.addEventListener("resize", this._onResize);
        };
        AudioEngine.prototype._moveButtonToTopLeft = function () {
            if (this._hostElement && this._muteButton) {
                this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
                this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
            }
        };
        AudioEngine.prototype._hideMuteButton = function () {
            if (this._muteButton) {
                document.body.removeChild(this._muteButton);
                this._muteButton = null;
            }
        };
        /**
         * Destroy and release the resources associated with the audio ccontext.
         */
        AudioEngine.prototype.dispose = function () {
            if (this.canUseWebAudio && this._audioContextInitialized) {
                if (this._connectedAnalyser && this._audioContext) {
                    this._connectedAnalyser.stopDebugCanvas();
                    this._connectedAnalyser.dispose();
                    this.masterGain.disconnect();
                    this.masterGain.connect(this._audioContext.destination);
                    this._connectedAnalyser = null;
                }
                this.masterGain.gain.value = 1;
            }
            this.WarnedWebAudioUnsupported = false;
            this._hideMuteButton();
            window.removeEventListener("resize", this._onResize);
            this.onAudioUnlockedObservable.clear();
            this.onAudioLockedObservable.clear();
        };
        /**
         * Gets the global volume sets on the master gain.
         * @returns the global volume if set or -1 otherwise
         */
        AudioEngine.prototype.getGlobalVolume = function () {
            if (this.canUseWebAudio && this._audioContextInitialized) {
                return this.masterGain.gain.value;
            }
            else {
                return -1;
            }
        };
        /**
         * Sets the global volume of your experience (sets on the master gain).
         * @param newVolume Defines the new global volume of the application
         */
        AudioEngine.prototype.setGlobalVolume = function (newVolume) {
            if (this.canUseWebAudio && this._audioContextInitialized) {
                this.masterGain.gain.value = newVolume;
            }
        };
        /**
         * Connect the audio engine to an audio analyser allowing some amazing
         * synchornization between the sounds/music and your visualization (VuMeter for instance).
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
         * @param analyser The analyser to connect to the engine
         */
        AudioEngine.prototype.connectToAnalyser = function (analyser) {
            if (this._connectedAnalyser) {
                this._connectedAnalyser.stopDebugCanvas();
            }
            if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
                this._connectedAnalyser = analyser;
                this.masterGain.disconnect();
                this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
            }
        };
        return AudioEngine;
    }());
    BABYLON.AudioEngine = AudioEngine;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.audioEngine.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Defines a sound that can be played in the application.
     * The sound can either be an ambient track or a simple sound played in reaction to a user action.
     * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
     */
    var Sound = /** @class */ (function () {
        /**
        * Create a sound and attach it to a scene
        * @param name Name of your sound
        * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
        * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
        * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
        */
        function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
            if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
            var _this = this;
            /**
             * Does the sound autoplay once loaded.
             */
            this.autoplay = false;
            /**
             * Does the sound loop after it finishes playing once.
             */
            this.loop = false;
            /**
             * Does the sound use a custom attenuation curve to simulate the falloff
             * happening when the source gets further away from the camera.
             * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
             */
            this.useCustomAttenuation = false;
            /**
             * Is this sound currently played.
             */
            this.isPlaying = false;
            /**
             * Is this sound currently paused.
             */
            this.isPaused = false;
            /**
             * Does this sound enables spatial sound.
             * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
             */
            this.spatialSound = false;
            /**
             * Define the reference distance the sound should be heard perfectly.
             * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
             */
            this.refDistance = 1;
            /**
             * Define the roll off factor of spatial sounds.
             * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
             */
            this.rolloffFactor = 1;
            /**
             * Define the max distance the sound should be heard (intensity just became 0 at this point).
             * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
             */
            this.maxDistance = 100;
            /**
             * Define the distance attenuation model the sound will follow.
             * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
             */
            this.distanceModel = "linear";
            /**
             * Observable event when the current playing sound finishes.
             */
            this.onEndedObservable = new BABYLON.Observable();
            this._panningModel = "equalpower";
            this._playbackRate = 1;
            this._streaming = false;
            this._startTime = 0;
            this._startOffset = 0;
            this._position = BABYLON.Vector3.Zero();
            /** @hidden */
            this._positionInEmitterSpace = false;
            this._localDirection = new BABYLON.Vector3(1, 0, 0);
            this._volume = 1;
            this._isReadyToPlay = false;
            this._isDirectional = false;
            // Used if you'd like to create a directional sound.
            // If not set, the sound will be omnidirectional
            this._coneInnerAngle = 360;
            this._coneOuterAngle = 360;
            this._coneOuterGain = 0;
            this._isOutputConnected = false;
            this._urlType = "Unknown";
            this.name = name;
            this._scene = scene;
            var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
            if (!compo) {
                compo = new BABYLON.AudioSceneComponent(scene);
                scene._addComponent(compo);
            }
            this._readyToPlayCallback = readyToPlayCallback;
            // Default custom attenuation function is a linear attenuation
            this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
                if (currentDistance < maxDistance) {
                    return currentVolume * (1 - currentDistance / maxDistance);
                }
                else {
                    return 0;
                }
            };
            if (options) {
                this.autoplay = options.autoplay || false;
                this.loop = options.loop || false;
                // if volume === 0, we need another way to check this option
                if (options.volume !== undefined) {
                    this._volume = options.volume;
                }
                this.spatialSound = options.spatialSound || false;
                this.maxDistance = options.maxDistance || 100;
                this.useCustomAttenuation = options.useCustomAttenuation || false;
                this.rolloffFactor = options.rolloffFactor || 1;
                this.refDistance = options.refDistance || 1;
                this.distanceModel = options.distanceModel || "linear";
                this._playbackRate = options.playbackRate || 1;
                this._streaming = options.streaming || false;
            }
            if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
                this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
                this._soundGain.gain.value = this._volume;
                this._inputAudioNode = this._soundGain;
                this._outputAudioNode = this._soundGain;
                if (this.spatialSound) {
                    this._createSpatialParameters();
                }
                this._scene.mainSoundTrack.AddSound(this);
                var validParameter = true;
                // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
                if (urlOrArrayBuffer) {
                    try {
                        if (typeof (urlOrArrayBuffer) === "string") {
                            this._urlType = "String";
                        }
                        else if (urlOrArrayBuffer instanceof ArrayBuffer) {
                            this._urlType = "ArrayBuffer";
                        }
                        else if (urlOrArrayBuffer instanceof MediaStream) {
                            this._urlType = "MediaStream";
                        }
                        else if (Array.isArray(urlOrArrayBuffer)) {
                            this._urlType = "Array";
                        }
                        var urls = [];
                        var codecSupportedFound = false;
                        switch (this._urlType) {
                            case "MediaStream":
                                this._streaming = true;
                                this._isReadyToPlay = true;
                                this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
                                if (this.autoplay) {
                                    this.play();
                                }
                                if (this._readyToPlayCallback) {
                                    this._readyToPlayCallback();
                                }
                                break;
                            case "ArrayBuffer":
                                if (urlOrArrayBuffer.byteLength > 0) {
                                    codecSupportedFound = true;
                                    this._soundLoaded(urlOrArrayBuffer);
                                }
                                break;
                            case "String":
                                urls.push(urlOrArrayBuffer);
                            case "Array":
                                if (urls.length === 0) {
                                    urls = urlOrArrayBuffer;
                                }
                                // If we found a supported format, we load it immediately and stop the loop
                                for (var i = 0; i < urls.length; i++) {
                                    var url = urls[i];
                                    if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
                                        codecSupportedFound = true;
                                    }
                                    if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
                                        codecSupportedFound = true;
                                    }
                                    if (url.indexOf(".wav", url.length - 4) !== -1) {
                                        codecSupportedFound = true;
                                    }
                                    if (url.indexOf("blob:") !== -1) {
                                        codecSupportedFound = true;
                                    }
                                    if (codecSupportedFound) {
                                        // Loading sound using XHR2
                                        if (!this._streaming) {
                                            this._scene._loadFile(url, function (data) {
                                                _this._soundLoaded(data);
                                            }, undefined, true, true, function (exception) {
                                                if (exception) {
                                                    BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
                                                }
                                                BABYLON.Tools.Error("Sound creation aborted.");
                                                _this._scene.mainSoundTrack.RemoveSound(_this);
                                            });
                                        }
                                        // Streaming sound using HTML5 Audio tag
                                        else {
                                            this._htmlAudioElement = new Audio(url);
                                            this._htmlAudioElement.controls = false;
                                            this._htmlAudioElement.loop = this.loop;
                                            BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
                                            this._htmlAudioElement.preload = "auto";
                                            this._htmlAudioElement.addEventListener("canplaythrough", function () {
                                                _this._isReadyToPlay = true;
                                                if (_this.autoplay) {
                                                    _this.play();
                                                }
                                                if (_this._readyToPlayCallback) {
                                                    _this._readyToPlayCallback();
                                                }
                                            });
                                            document.body.appendChild(this._htmlAudioElement);
                                            this._htmlAudioElement.load();
                                        }
                                        break;
                                    }
                                }
                                break;
                            default:
                                validParameter = false;
                                break;
                        }
                        if (!validParameter) {
                            BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
                        }
                        else {
                            if (!codecSupportedFound) {
                                this._isReadyToPlay = true;
                                // Simulating a ready to play event to avoid breaking code path
                                if (this._readyToPlayCallback) {
                                    window.setTimeout(function () {
                                        if (_this._readyToPlayCallback) {
                                            _this._readyToPlayCallback();
                                        }
                                    }, 1000);
                                }
                            }
                        }
                    }
                    catch (ex) {
                        BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
                        this._scene.mainSoundTrack.RemoveSound(this);
                    }
                }
            }
            else {
                // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
                this._scene.mainSoundTrack.AddSound(this);
                if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
                    BABYLON.Tools.Error("Web Audio is not supported by your browser.");
                    BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
                }
                // Simulating a ready to play event to avoid breaking code for non web audio browsers
                if (this._readyToPlayCallback) {
                    window.setTimeout(function () {
                        if (_this._readyToPlayCallback) {
                            _this._readyToPlayCallback();
                        }
                    }, 1000);
                }
            }
        }
        /**
         * Release the sound and its associated resources
         */
        Sound.prototype.dispose = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (this.isPlaying) {
                    this.stop();
                }
                this._isReadyToPlay = false;
                if (this.soundTrackId === -1) {
                    this._scene.mainSoundTrack.RemoveSound(this);
                }
                else if (this._scene.soundTracks) {
                    this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
                }
                if (this._soundGain) {
                    this._soundGain.disconnect();
                    this._soundGain = null;
                }
                if (this._soundPanner) {
                    this._soundPanner.disconnect();
                    this._soundPanner = null;
                }
                if (this._soundSource) {
                    this._soundSource.disconnect();
                    this._soundSource = null;
                }
                this._audioBuffer = null;
                if (this._htmlAudioElement) {
                    this._htmlAudioElement.pause();
                    this._htmlAudioElement.src = "";
                    document.body.removeChild(this._htmlAudioElement);
                }
                if (this._streamingSource) {
                    this._streamingSource.disconnect();
                }
                if (this._connectedMesh && this._registerFunc) {
                    this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
                    this._connectedMesh = null;
                }
            }
        };
        /**
         * Gets if the sounds is ready to be played or not.
         * @returns true if ready, otherwise false
         */
        Sound.prototype.isReady = function () {
            return this._isReadyToPlay;
        };
        Sound.prototype._soundLoaded = function (audioData) {
            var _this = this;
            if (!BABYLON.Engine.audioEngine.audioContext) {
                return;
            }
            BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
                _this._audioBuffer = buffer;
                _this._isReadyToPlay = true;
                if (_this.autoplay) {
                    _this.play();
                }
                if (_this._readyToPlayCallback) {
                    _this._readyToPlayCallback();
                }
            }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
        };
        /**
         * Sets the data of the sound from an audiobuffer
         * @param audioBuffer The audioBuffer containing the data
         */
        Sound.prototype.setAudioBuffer = function (audioBuffer) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                this._audioBuffer = audioBuffer;
                this._isReadyToPlay = true;
            }
        };
        /**
         * Updates the current sounds options such as maxdistance, loop...
         * @param options A JSON object containing values named as the object properties
         */
        Sound.prototype.updateOptions = function (options) {
            if (options) {
                this.loop = options.loop || this.loop;
                this.maxDistance = options.maxDistance || this.maxDistance;
                this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
                this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
                this.refDistance = options.refDistance || this.refDistance;
                this.distanceModel = options.distanceModel || this.distanceModel;
                this._playbackRate = options.playbackRate || this._playbackRate;
                this._updateSpatialParameters();
                if (this.isPlaying) {
                    if (this._streaming && this._htmlAudioElement) {
                        this._htmlAudioElement.playbackRate = this._playbackRate;
                    }
                    else {
                        if (this._soundSource) {
                            this._soundSource.playbackRate.value = this._playbackRate;
                        }
                    }
                }
            }
        };
        Sound.prototype._createSpatialParameters = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
                if (this._scene.headphone) {
                    this._panningModel = "HRTF";
                }
                this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
                this._updateSpatialParameters();
                this._soundPanner.connect(this._outputAudioNode);
                this._inputAudioNode = this._soundPanner;
            }
        };
        Sound.prototype._updateSpatialParameters = function () {
            if (this.spatialSound && this._soundPanner) {
                if (this.useCustomAttenuation) {
                    // Tricks to disable in a way embedded Web Audio attenuation
                    this._soundPanner.distanceModel = "linear";
                    this._soundPanner.maxDistance = Number.MAX_VALUE;
                    this._soundPanner.refDistance = 1;
                    this._soundPanner.rolloffFactor = 1;
                    this._soundPanner.panningModel = this._panningModel;
                }
                else {
                    this._soundPanner.distanceModel = this.distanceModel;
                    this._soundPanner.maxDistance = this.maxDistance;
                    this._soundPanner.refDistance = this.refDistance;
                    this._soundPanner.rolloffFactor = this.rolloffFactor;
                    this._soundPanner.panningModel = this._panningModel;
                }
            }
        };
        /**
         * Switch the panning model to HRTF:
         * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
         */
        Sound.prototype.switchPanningModelToHRTF = function () {
            this._panningModel = "HRTF";
            this._switchPanningModel();
        };
        /**
         * Switch the panning model to Equal Power:
         * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
         */
        Sound.prototype.switchPanningModelToEqualPower = function () {
            this._panningModel = "equalpower";
            this._switchPanningModel();
        };
        Sound.prototype._switchPanningModel = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
                this._soundPanner.panningModel = this._panningModel;
            }
        };
        /**
         * Connect this sound to a sound track audio node like gain...
         * @param soundTrackAudioNode the sound track audio node to connect to
         */
        Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (this._isOutputConnected) {
                    this._outputAudioNode.disconnect();
                }
                this._outputAudioNode.connect(soundTrackAudioNode);
                this._isOutputConnected = true;
            }
        };
        /**
        * Transform this sound into a directional source
        * @param coneInnerAngle Size of the inner cone in degree
        * @param coneOuterAngle Size of the outer cone in degree
        * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
        */
        Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
            if (coneOuterAngle < coneInnerAngle) {
                BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
                return;
            }
            this._coneInnerAngle = coneInnerAngle;
            this._coneOuterAngle = coneOuterAngle;
            this._coneOuterGain = coneOuterGain;
            this._isDirectional = true;
            if (this.isPlaying && this.loop) {
                this.stop();
                this.play();
            }
        };
        Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
            /**
             * Gets or sets the inner angle for the directional cone.
             */
            get: function () {
                return this._coneInnerAngle;
            },
            /**
             * Gets or sets the inner angle for the directional cone.
             */
            set: function (value) {
                if (value != this._coneInnerAngle) {
                    if (this._coneOuterAngle < value) {
                        BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
                        return;
                    }
                    this._coneInnerAngle = value;
                    if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
                        this._soundPanner.coneInnerAngle = this._coneInnerAngle;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
            /**
             * Gets or sets the outer angle for the directional cone.
             */
            get: function () {
                return this._coneOuterAngle;
            },
            /**
             * Gets or sets the outer angle for the directional cone.
             */
            set: function (value) {
                if (value != this._coneOuterAngle) {
                    if (value < this._coneInnerAngle) {
                        BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
                        return;
                    }
                    this._coneOuterAngle = value;
                    if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
                        this._soundPanner.coneOuterAngle = this._coneOuterAngle;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Sets the position of the emitter if spatial sound is enabled
         * @param newPosition Defines the new posisiton
         */
        Sound.prototype.setPosition = function (newPosition) {
            this._position = newPosition;
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
                this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
            }
        };
        /**
         * Sets the local direction of the emitter if spatial sound is enabled
         * @param newLocalDirection Defines the new local direction
         */
        Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
            this._localDirection = newLocalDirection;
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
                this._updateDirection();
            }
        };
        Sound.prototype._updateDirection = function () {
            if (!this._connectedMesh || !this._soundPanner) {
                return;
            }
            var mat = this._connectedMesh.getWorldMatrix();
            var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
            direction.normalize();
            this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
        };
        /** @hidden */
        Sound.prototype.updateDistanceFromListener = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
                var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
                this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
            }
        };
        /**
         * Sets a new custom attenuation function for the sound.
         * @param callback Defines the function used for the attenuation
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
         */
        Sound.prototype.setAttenuationFunction = function (callback) {
            this._customAttenuationFunction = callback;
        };
        /**
        * Play the sound
        * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
        * @param offset (optional) Start the sound setting it at a specific time
        */
        Sound.prototype.play = function (time, offset) {
            var _this = this;
            if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
                try {
                    if (this._startOffset < 0) {
                        time = -this._startOffset;
                        this._startOffset = 0;
                    }
                    var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
                    if (!this._soundSource || !this._streamingSource) {
                        if (this.spatialSound && this._soundPanner) {
                            if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
                                this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
                            }
                            if (this._isDirectional) {
                                this._soundPanner.coneInnerAngle = this._coneInnerAngle;
                                this._soundPanner.coneOuterAngle = this._coneOuterAngle;
                                this._soundPanner.coneOuterGain = this._coneOuterGain;
                                if (this._connectedMesh) {
                                    this._updateDirection();
                                }
                                else {
                                    this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
                                }
                            }
                        }
                    }
                    if (this._streaming) {
                        if (!this._streamingSource) {
                            this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
                            this._htmlAudioElement.onended = function () { _this._onended(); };
                            this._htmlAudioElement.playbackRate = this._playbackRate;
                        }
                        this._streamingSource.disconnect();
                        this._streamingSource.connect(this._inputAudioNode);
                        if (this._htmlAudioElement) {
                            // required to manage properly the new suspended default state of Chrome
                            // When the option 'streaming: true' is used, we need first to wait for
                            // the audio engine to be unlocked by a user gesture before trying to play
                            // an HTML Audio elememt
                            var tryToPlay = function () {
                                if (BABYLON.Engine.audioEngine.unlocked) {
                                    var playPromise = _this._htmlAudioElement.play();
                                    // In browsers that don’t yet support this functionality,
                                    // playPromise won’t be defined.
                                    if (playPromise !== undefined) {
                                        playPromise.catch(function (error) {
                                            // Automatic playback failed.
                                            // Waiting for the audio engine to be unlocked by user click on unmute
                                            BABYLON.Engine.audioEngine.lock();
                                            BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
                                        });
                                    }
                                }
                                else {
                                    BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
                                }
                            };
                            tryToPlay();
                        }
                    }
                    else {
                        this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
                        this._soundSource.buffer = this._audioBuffer;
                        this._soundSource.connect(this._inputAudioNode);
                        this._soundSource.loop = this.loop;
                        this._soundSource.playbackRate.value = this._playbackRate;
                        this._soundSource.onended = function () { _this._onended(); };
                        if (this._soundSource.buffer) {
                            this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
                        }
                    }
                    this._startTime = startTime;
                    this.isPlaying = true;
                    this.isPaused = false;
                }
                catch (ex) {
                    BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
                }
            }
        };
        Sound.prototype._onended = function () {
            this.isPlaying = false;
            if (this.onended) {
                this.onended();
            }
            this.onEndedObservable.notifyObservers(this);
        };
        /**
        * Stop the sound
        * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
        */
        Sound.prototype.stop = function (time) {
            if (this.isPlaying) {
                if (this._streaming) {
                    if (this._htmlAudioElement) {
                        this._htmlAudioElement.pause();
                        // Test needed for Firefox or it will generate an Invalid State Error
                        if (this._htmlAudioElement.currentTime > 0) {
                            this._htmlAudioElement.currentTime = 0;
                        }
                    }
                    else {
                        this._streamingSource.disconnect();
                    }
                }
                else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
                    var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
                    this._soundSource.stop(stopTime);
                    this._soundSource.onended = function () { };
                    if (!this.isPaused) {
                        this._startOffset = 0;
                    }
                }
                this.isPlaying = false;
            }
        };
        /**
         * Put the sound in pause
         */
        Sound.prototype.pause = function () {
            if (this.isPlaying) {
                this.isPaused = true;
                if (this._streaming) {
                    if (this._htmlAudioElement) {
                        this._htmlAudioElement.pause();
                    }
                    else {
                        this._streamingSource.disconnect();
                    }
                }
                else if (BABYLON.Engine.audioEngine.audioContext) {
                    this.stop(0);
                    this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
                }
            }
        };
        /**
         * Sets a dedicated volume for this sounds
         * @param newVolume Define the new volume of the sound
         * @param time Define in how long the sound should be at this value
         */
        Sound.prototype.setVolume = function (newVolume, time) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
                if (time && BABYLON.Engine.audioEngine.audioContext) {
                    this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
                    this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
                    this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
                }
                else {
                    this._soundGain.gain.value = newVolume;
                }
            }
            this._volume = newVolume;
        };
        /**
         * Set the sound play back rate
         * @param newPlaybackRate Define the playback rate the sound should be played at
         */
        Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
            this._playbackRate = newPlaybackRate;
            if (this.isPlaying) {
                if (this._streaming && this._htmlAudioElement) {
                    this._htmlAudioElement.playbackRate = this._playbackRate;
                }
                else if (this._soundSource) {
                    this._soundSource.playbackRate.value = this._playbackRate;
                }
            }
        };
        /**
         * Gets the volume of the sound.
         * @returns the volume of the sound
         */
        Sound.prototype.getVolume = function () {
            return this._volume;
        };
        /**
         * Attach the sound to a dedicated mesh
         * @param meshToConnectTo The mesh to connect the sound with
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
         */
        Sound.prototype.attachToMesh = function (meshToConnectTo) {
            var _this = this;
            if (this._connectedMesh && this._registerFunc) {
                this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
                this._registerFunc = null;
            }
            this._connectedMesh = meshToConnectTo;
            if (!this.spatialSound) {
                this.spatialSound = true;
                this._createSpatialParameters();
                if (this.isPlaying && this.loop) {
                    this.stop();
                    this.play();
                }
            }
            this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
            this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
            meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
        };
        /**
         * Detach the sound from the previously attached mesh
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
         */
        Sound.prototype.detachFromMesh = function () {
            if (this._connectedMesh && this._registerFunc) {
                this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
                this._registerFunc = null;
                this._connectedMesh = null;
            }
        };
        Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
            if (!node.getBoundingInfo) {
                return;
            }
            var mesh = node;
            if (this._positionInEmitterSpace) {
                mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
                this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
            }
            else {
                var boundingInfo = mesh.getBoundingInfo();
                this.setPosition(boundingInfo.boundingSphere.centerWorld);
            }
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
                this._updateDirection();
            }
        };
        /**
         * Clone the current sound in the scene.
         * @returns the new sound clone
         */
        Sound.prototype.clone = function () {
            var _this = this;
            if (!this._streaming) {
                var setBufferAndRun = function () {
                    if (_this._isReadyToPlay) {
                        clonedSound._audioBuffer = _this.getAudioBuffer();
                        clonedSound._isReadyToPlay = true;
                        if (clonedSound.autoplay) {
                            clonedSound.play();
                        }
                    }
                    else {
                        window.setTimeout(setBufferAndRun, 300);
                    }
                };
                var currentOptions = {
                    autoplay: this.autoplay, loop: this.loop,
                    volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
                    useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
                    refDistance: this.refDistance, distanceModel: this.distanceModel
                };
                var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
                if (this.useCustomAttenuation) {
                    clonedSound.setAttenuationFunction(this._customAttenuationFunction);
                }
                clonedSound.setPosition(this._position);
                clonedSound.setPlaybackRate(this._playbackRate);
                setBufferAndRun();
                return clonedSound;
            }
            // Can't clone a streaming sound
            else {
                return null;
            }
        };
        /**
         * Gets the current underlying audio buffer containing the data
         * @returns the audio buffer
         */
        Sound.prototype.getAudioBuffer = function () {
            return this._audioBuffer;
        };
        /**
         * Serializes the Sound in a JSON representation
         * @returns the JSON representation of the sound
         */
        Sound.prototype.serialize = function () {
            var serializationObject = {
                name: this.name,
                url: this.name,
                autoplay: this.autoplay,
                loop: this.loop,
                volume: this._volume,
                spatialSound: this.spatialSound,
                maxDistance: this.maxDistance,
                rolloffFactor: this.rolloffFactor,
                refDistance: this.refDistance,
                distanceModel: this.distanceModel,
                playbackRate: this._playbackRate,
                panningModel: this._panningModel,
                soundTrackId: this.soundTrackId
            };
            if (this.spatialSound) {
                if (this._connectedMesh) {
                    serializationObject.connectedMeshId = this._connectedMesh.id;
                }
                serializationObject.position = this._position.asArray();
                serializationObject.refDistance = this.refDistance;
                serializationObject.distanceModel = this.distanceModel;
                serializationObject.isDirectional = this._isDirectional;
                serializationObject.localDirectionToMesh = this._localDirection.asArray();
                serializationObject.coneInnerAngle = this._coneInnerAngle;
                serializationObject.coneOuterAngle = this._coneOuterAngle;
                serializationObject.coneOuterGain = this._coneOuterGain;
            }
            return serializationObject;
        };
        /**
         * Parse a JSON representation of a sound to innstantiate in a given scene
         * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
         * @param scene Define the scene the new parsed sound should be created in
         * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
         * @param sourceSound Define a cound place holder if do not need to instantiate a new one
         * @returns the newly parsed sound
         */
        Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
            var soundName = parsedSound.name;
            var soundUrl;
            if (parsedSound.url) {
                soundUrl = rootUrl + parsedSound.url;
            }
            else {
                soundUrl = rootUrl + soundName;
            }
            var options = {
                autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
                spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
                rolloffFactor: parsedSound.rolloffFactor,
                refDistance: parsedSound.refDistance,
                distanceModel: parsedSound.distanceModel,
                playbackRate: parsedSound.playbackRate
            };
            var newSound;
            if (!sourceSound) {
                newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
                scene._addPendingData(newSound);
            }
            else {
                var setBufferAndRun = function () {
                    if (sourceSound._isReadyToPlay) {
                        newSound._audioBuffer = sourceSound.getAudioBuffer();
                        newSound._isReadyToPlay = true;
                        if (newSound.autoplay) {
                            newSound.play();
                        }
                    }
                    else {
                        window.setTimeout(setBufferAndRun, 300);
                    }
                };
                newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
                setBufferAndRun();
            }
            if (parsedSound.position) {
                var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
                newSound.setPosition(soundPosition);
            }
            if (parsedSound.isDirectional) {
                newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
                if (parsedSound.localDirectionToMesh) {
                    var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
                    newSound.setLocalDirectionToMesh(localDirectionToMesh);
                }
            }
            if (parsedSound.connectedMeshId) {
                var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
                if (connectedMesh) {
                    newSound.attachToMesh(connectedMesh);
                }
            }
            return newSound;
        };
        return Sound;
    }());
    BABYLON.Sound = Sound;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sound.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
     * It will be also used in a future release to apply effects on a specific track.
     * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
     */
    var SoundTrack = /** @class */ (function () {
        /**
         * Creates a new sound track.
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
         * @param scene Define the scene the sound track belongs to
         * @param options
         */
        function SoundTrack(scene, options) {
            if (options === void 0) { options = {}; }
            /**
             * The unique identifier of the sound track in the scene.
             */
            this.id = -1;
            this._isMainTrack = false;
            this._isInitialized = false;
            this._scene = scene;
            this.soundCollection = new Array();
            this._options = options;
            if (!this._isMainTrack && this._scene.soundTracks) {
                this._scene.soundTracks.push(this);
                this.id = this._scene.soundTracks.length - 1;
            }
        }
        SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
                this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
                this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
                if (this._options) {
                    if (this._options.volume) {
                        this._outputAudioNode.gain.value = this._options.volume;
                    }
                    if (this._options.mainTrack) {
                        this._isMainTrack = this._options.mainTrack;
                    }
                }
                this._isInitialized = true;
            }
        };
        /**
         * Release the sound track and its associated resources
         */
        SoundTrack.prototype.dispose = function () {
            if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
                if (this._connectedAnalyser) {
                    this._connectedAnalyser.stopDebugCanvas();
                }
                while (this.soundCollection.length) {
                    this.soundCollection[0].dispose();
                }
                if (this._outputAudioNode) {
                    this._outputAudioNode.disconnect();
                }
                this._outputAudioNode = null;
            }
        };
        /**
         * Adds a sound to this sound track
         * @param sound define the cound to add
         * @ignoreNaming
         */
        SoundTrack.prototype.AddSound = function (sound) {
            if (!this._isInitialized) {
                this._initializeSoundTrackAudioGraph();
            }
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
                sound.connectToSoundTrackAudioNode(this._outputAudioNode);
            }
            if (sound.soundTrackId) {
                if (sound.soundTrackId === -1) {
                    this._scene.mainSoundTrack.RemoveSound(sound);
                }
                else if (this._scene.soundTracks) {
                    this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
                }
            }
            this.soundCollection.push(sound);
            sound.soundTrackId = this.id;
        };
        /**
         * Removes a sound to this sound track
         * @param sound define the cound to remove
         * @ignoreNaming
         */
        SoundTrack.prototype.RemoveSound = function (sound) {
            var index = this.soundCollection.indexOf(sound);
            if (index !== -1) {
                this.soundCollection.splice(index, 1);
            }
        };
        /**
         * Set a global volume for the full sound track.
         * @param newVolume Define the new volume of the sound track
         */
        SoundTrack.prototype.setVolume = function (newVolume) {
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
                this._outputAudioNode.gain.value = newVolume;
            }
        };
        /**
         * Switch the panning model to HRTF:
         * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
         */
        SoundTrack.prototype.switchPanningModelToHRTF = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                for (var i = 0; i < this.soundCollection.length; i++) {
                    this.soundCollection[i].switchPanningModelToHRTF();
                }
            }
        };
        /**
         * Switch the panning model to Equal Power:
         * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
         */
        SoundTrack.prototype.switchPanningModelToEqualPower = function () {
            if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                for (var i = 0; i < this.soundCollection.length; i++) {
                    this.soundCollection[i].switchPanningModelToEqualPower();
                }
            }
        };
        /**
         * Connect the sound track to an audio analyser allowing some amazing
         * synchornization between the sounds/music and your visualization (VuMeter for instance).
         * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
         * @param analyser The analyser to connect to the engine
         */
        SoundTrack.prototype.connectToAnalyser = function (analyser) {
            if (this._connectedAnalyser) {
                this._connectedAnalyser.stopDebugCanvas();
            }
            this._connectedAnalyser = analyser;
            if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
                this._outputAudioNode.disconnect();
                this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
            }
        };
        return SoundTrack;
    }());
    BABYLON.SoundTrack = SoundTrack;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.soundtrack.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to work with sound analyzer using fast fourier transform (FFT)
     * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
     */
    var Analyser = /** @class */ (function () {
        /**
         * Creates a new analyser
         * @param scene defines hosting scene
         */
        function Analyser(scene) {
            /**
             * Gets or sets the smoothing
             * @ignorenaming
             */
            this.SMOOTHING = 0.75;
            /**
             * Gets or sets the FFT table size
             * @ignorenaming
             */
            this.FFT_SIZE = 512;
            /**
             * Gets or sets the bar graph amplitude
             * @ignorenaming
             */
            this.BARGRAPHAMPLITUDE = 256;
            /**
             * Gets or sets the position of the debug canvas
             * @ignorenaming
             */
            this.DEBUGCANVASPOS = { x: 20, y: 20 };
            /**
             * Gets or sets the debug canvas size
             * @ignorenaming
             */
            this.DEBUGCANVASSIZE = { width: 320, height: 200 };
            this._scene = scene;
            this._audioEngine = BABYLON.Engine.audioEngine;
            if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
                this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
                this._webAudioAnalyser.minDecibels = -140;
                this._webAudioAnalyser.maxDecibels = 0;
                this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
                this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
                this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
            }
        }
        /**
         * Get the number of data values you will have to play with for the visualization
         * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
         * @returns a number
         */
        Analyser.prototype.getFrequencyBinCount = function () {
            if (this._audioEngine.canUseWebAudio) {
                return this._webAudioAnalyser.frequencyBinCount;
            }
            else {
                return 0;
            }
        };
        /**
         * Gets the current frequency data as a byte array
         * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
         * @returns a Uint8Array
         */
        Analyser.prototype.getByteFrequencyData = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
                this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
            }
            return this._byteFreqs;
        };
        /**
         * Gets the current waveform as a byte array
         * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
         * @returns a Uint8Array
         */
        Analyser.prototype.getByteTimeDomainData = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
                this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
            }
            return this._byteTime;
        };
        /**
         * Gets the current frequency data as a float array
         * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
         * @returns a Float32Array
         */
        Analyser.prototype.getFloatFrequencyData = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
                this._webAudioAnalyser.fftSize = this.FFT_SIZE;
                this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
            }
            return this._floatFreqs;
        };
        /**
         * Renders the debug canvas
         */
        Analyser.prototype.drawDebugCanvas = function () {
            var _this = this;
            if (this._audioEngine.canUseWebAudio) {
                if (!this._debugCanvas) {
                    this._debugCanvas = document.createElement("canvas");
                    this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
                    this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
                    this._debugCanvas.style.position = "absolute";
                    this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
                    this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
                    this._debugCanvasContext = this._debugCanvas.getContext("2d");
                    document.body.appendChild(this._debugCanvas);
                    this._registerFunc = function () {
                        _this.drawDebugCanvas();
                    };
                    this._scene.registerBeforeRender(this._registerFunc);
                }
                if (this._registerFunc && this._debugCanvasContext) {
                    var workingArray = this.getByteFrequencyData();
                    this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
                    this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
                    // Draw the frequency domain chart.
                    for (var i = 0; i < this.getFrequencyBinCount(); i++) {
                        var value = workingArray[i];
                        var percent = value / this.BARGRAPHAMPLITUDE;
                        var height = this.DEBUGCANVASSIZE.height * percent;
                        var offset = this.DEBUGCANVASSIZE.height - height - 1;
                        var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
                        var hue = i / this.getFrequencyBinCount() * 360;
                        this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
                        this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
                    }
                }
            }
        };
        /**
         * Stops rendering the debug canvas and removes it
         */
        Analyser.prototype.stopDebugCanvas = function () {
            if (this._debugCanvas) {
                if (this._registerFunc) {
                    this._scene.unregisterBeforeRender(this._registerFunc);
                    this._registerFunc = null;
                }
                document.body.removeChild(this._debugCanvas);
                this._debugCanvas = null;
                this._debugCanvasContext = null;
            }
        };
        /**
         * Connects two audio nodes
         * @param inputAudioNode defines first node to connect
         * @param outputAudioNode defines second node to connect
         */
        Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
            if (this._audioEngine.canUseWebAudio) {
                inputAudioNode.connect(this._webAudioAnalyser);
                this._webAudioAnalyser.connect(outputAudioNode);
            }
        };
        /**
         * Releases all associated resources
         */
        Analyser.prototype.dispose = function () {
            if (this._audioEngine.canUseWebAudio) {
                this._webAudioAnalyser.disconnect();
            }
        };
        return Analyser;
    }());
    BABYLON.Analyser = Analyser;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.analyser.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Wraps one or more Sound objects and selects one with random weight for playback.
     */
    var WeightedSound = /** @class */ (function () {
        /**
         * Creates a new WeightedSound from the list of sounds given.
         * @param loop When true a Sound will be selected and played when the current playing Sound completes.
         * @param sounds Array of Sounds that will be selected from.
         * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
         */
        function WeightedSound(loop, sounds, weights) {
            var _this = this;
            /** When true a Sound will be selected and played when the current playing Sound completes. */
            this.loop = false;
            this._coneInnerAngle = 360;
            this._coneOuterAngle = 360;
            this._volume = 1;
            /** A Sound is currently playing. */
            this.isPlaying = false;
            /** A Sound is currently paused. */
            this.isPaused = false;
            this._sounds = [];
            this._weights = [];
            if (sounds.length !== weights.length) {
                throw new Error('Sounds length does not equal weights length');
            }
            this.loop = loop;
            this._weights = weights;
            // Normalize the weights
            var weightSum = 0;
            for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
                var weight = weights_1[_i];
                weightSum += weight;
            }
            var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
            for (var i = 0; i < this._weights.length; i++) {
                this._weights[i] *= invWeightSum;
            }
            this._sounds = sounds;
            for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
                var sound = _b[_a];
                sound.onEndedObservable.add(function () { _this._onended(); });
            }
        }
        Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
            /**
             * The size of cone in degrees for a directional sound in which there will be no attenuation.
             */
            get: function () {
                return this._coneInnerAngle;
            },
            /**
             * The size of cone in degress for a directional sound in which there will be no attenuation.
             */
            set: function (value) {
                if (value !== this._coneInnerAngle) {
                    if (this._coneOuterAngle < value) {
                        BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
                        return;
                    }
                    this._coneInnerAngle = value;
                    for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
                        var sound = _a[_i];
                        sound.directionalConeInnerAngle = value;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
            /**
             * Size of cone in degrees for a directional sound outside of which there will be no sound.
             * Listener angles between innerAngle and outerAngle will falloff linearly.
             */
            get: function () {
                return this._coneOuterAngle;
            },
            /**
             * Size of cone in degrees for a directional sound outside of which there will be no sound.
             * Listener angles between innerAngle and outerAngle will falloff linearly.
             */
            set: function (value) {
                if (value !== this._coneOuterAngle) {
                    if (value < this._coneInnerAngle) {
                        BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
                        return;
                    }
                    this._coneOuterAngle = value;
                    for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
                        var sound = _a[_i];
                        sound.directionalConeOuterAngle = value;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WeightedSound.prototype, "volume", {
            /**
             * Playback volume.
             */
            get: function () {
                return this._volume;
            },
            /**
             * Playback volume.
             */
            set: function (value) {
                if (value !== this._volume) {
                    for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
                        var sound = _a[_i];
                        sound.setVolume(value);
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        WeightedSound.prototype._onended = function () {
            if (this._currentIndex !== undefined) {
                this._sounds[this._currentIndex].autoplay = false;
            }
            if (this.loop && this.isPlaying) {
                this.play();
            }
            else {
                this.isPlaying = false;
            }
        };
        /**
         * Suspend playback
         */
        WeightedSound.prototype.pause = function () {
            this.isPaused = true;
            if (this._currentIndex !== undefined) {
                this._sounds[this._currentIndex].pause();
            }
        };
        /**
         * Stop playback
         */
        WeightedSound.prototype.stop = function () {
            this.isPlaying = false;
            if (this._currentIndex !== undefined) {
                this._sounds[this._currentIndex].stop();
            }
        };
        /**
         * Start playback.
         * @param startOffset Position the clip head at a specific time in seconds.
         */
        WeightedSound.prototype.play = function (startOffset) {
            if (!this.isPaused) {
                this.stop();
                var randomValue = Math.random();
                var total = 0;
                for (var i = 0; i < this._weights.length; i++) {
                    total += this._weights[i];
                    if (randomValue <= total) {
                        this._currentIndex = i;
                        break;
                    }
                }
            }
            var sound = this._sounds[this._currentIndex];
            if (sound.isReady()) {
                sound.play(0, this.isPaused ? undefined : startOffset);
            }
            else {
                sound.autoplay = true;
            }
            this.isPlaying = true;
            this.isPaused = false;
        };
        return WeightedSound;
    }());
    BABYLON.WeightedSound = WeightedSound;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.weightedsound.js.map

var BABYLON;
(function (BABYLON) {
    // Adds the parser to the scene parsers.
    BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
        // TODO: add sound
        var loadedSounds = [];
        var loadedSound;
        container.sounds = container.sounds || [];
        if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
            for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
                var parsedSound = parsedData.sounds[index];
                if (BABYLON.Engine.audioEngine.canUseWebAudio) {
                    if (!parsedSound.url) {
                        parsedSound.url = parsedSound.name;
                    }
                    if (!loadedSounds[parsedSound.url]) {
                        loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
                        loadedSounds[parsedSound.url] = loadedSound;
                        container.sounds.push(loadedSound);
                    }
                    else {
                        container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
                    }
                }
                else {
                    container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
                }
            }
        }
        loadedSounds = [];
    });
    Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
        get: function () {
            var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
            if (!compo) {
                compo = new AudioSceneComponent(this);
                this._addComponent(compo);
            }
            if (!this._mainSoundTrack) {
                this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
            }
            return this._mainSoundTrack;
        },
        enumerable: true,
        configurable: true
    });
    BABYLON.Scene.prototype.getSoundByName = function (name) {
        var index;
        for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
            if (this.mainSoundTrack.soundCollection[index].name === name) {
                return this.mainSoundTrack.soundCollection[index];
            }
        }
        if (this.soundTracks) {
            for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
                for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
                    if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
                        return this.soundTracks[sdIndex].soundCollection[index];
                    }
                }
            }
        }
        return null;
    };
    Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
        get: function () {
            var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
            if (!compo) {
                compo = new AudioSceneComponent(this);
                this._addComponent(compo);
            }
            return compo.audioEnabled;
        },
        set: function (value) {
            var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
            if (!compo) {
                compo = new AudioSceneComponent(this);
                this._addComponent(compo);
            }
            if (value) {
                compo.enableAudio();
            }
            else {
                compo.disableAudio();
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
        get: function () {
            var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
            if (!compo) {
                compo = new AudioSceneComponent(this);
                this._addComponent(compo);
            }
            return compo.headphone;
        },
        set: function (value) {
            var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
            if (!compo) {
                compo = new AudioSceneComponent(this);
                this._addComponent(compo);
            }
            if (value) {
                compo.switchAudioModeForHeadphones();
            }
            else {
                compo.switchAudioModeForNormalSpeakers();
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Defines the sound scene component responsible to manage any sounds
     * in a given scene.
     */
    var AudioSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function AudioSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
            this._audioEnabled = true;
            this._headphone = false;
            this.scene = scene;
            scene.soundTracks = new Array();
            scene.sounds = new Array();
        }
        Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
            /**
             * Gets whether audio is enabled or not.
             * Please use related enable/disable method to switch state.
             */
            get: function () {
                return this._audioEnabled;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
            /**
             * Gets whether audio is outputing to headphone or not.
             * Please use the according Switch methods to change output.
             */
            get: function () {
                return this._headphone;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Registers the component in a given scene
         */
        AudioSceneComponent.prototype.register = function () {
            this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        AudioSceneComponent.prototype.rebuild = function () {
            // Nothing to do here. (Not rendering related)
        };
        /**
         * Serializes the component data to the specified json object
         * @param serializationObject The object to serialize to
         */
        AudioSceneComponent.prototype.serialize = function (serializationObject) {
            serializationObject.sounds = [];
            if (this.scene.soundTracks) {
                for (var index = 0; index < this.scene.soundTracks.length; index++) {
                    var soundtrack = this.scene.soundTracks[index];
                    for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
                        serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
                    }
                }
            }
        };
        /**
         * Adds all the element from the container to the scene
         * @param container the container holding the elements
         */
        AudioSceneComponent.prototype.addFromContainer = function (container) {
            var _this = this;
            if (!container.sounds) {
                return;
            }
            container.sounds.forEach(function (sound) {
                sound.play();
                sound.autoplay = true;
                _this.scene.mainSoundTrack.AddSound(sound);
            });
        };
        /**
         * Removes all the elements in the container from the scene
         * @param container contains the elements to remove
         */
        AudioSceneComponent.prototype.removeFromContainer = function (container) {
            var _this = this;
            if (!container.sounds) {
                return;
            }
            container.sounds.forEach(function (sound) {
                sound.stop();
                sound.autoplay = false;
                _this.scene.mainSoundTrack.RemoveSound(sound);
            });
        };
        /**
         * Disposes the component and the associated ressources.
         */
        AudioSceneComponent.prototype.dispose = function () {
            var scene = this.scene;
            if (scene._mainSoundTrack) {
                scene.mainSoundTrack.dispose();
            }
            if (scene.soundTracks) {
                for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
                    scene.soundTracks[scIndex].dispose();
                }
            }
        };
        /**
         * Disables audio in the associated scene.
         */
        AudioSceneComponent.prototype.disableAudio = function () {
            var scene = this.scene;
            this._audioEnabled = false;
            var i;
            for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
                scene.mainSoundTrack.soundCollection[i].pause();
            }
            if (scene.soundTracks) {
                for (i = 0; i < scene.soundTracks.length; i++) {
                    for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
                        scene.soundTracks[i].soundCollection[j].pause();
                    }
                }
            }
        };
        /**
         * Enables audio in the associated scene.
         */
        AudioSceneComponent.prototype.enableAudio = function () {
            var scene = this.scene;
            this._audioEnabled = true;
            var i;
            for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
                if (scene.mainSoundTrack.soundCollection[i].isPaused) {
                    scene.mainSoundTrack.soundCollection[i].play();
                }
            }
            if (scene.soundTracks) {
                for (i = 0; i < scene.soundTracks.length; i++) {
                    for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
                        if (scene.soundTracks[i].soundCollection[j].isPaused) {
                            scene.soundTracks[i].soundCollection[j].play();
                        }
                    }
                }
            }
        };
        /**
         * Switch audio to headphone output.
         */
        AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
            var scene = this.scene;
            this._headphone = true;
            scene.mainSoundTrack.switchPanningModelToHRTF();
            if (scene.soundTracks) {
                for (var i = 0; i < scene.soundTracks.length; i++) {
                    scene.soundTracks[i].switchPanningModelToHRTF();
                }
            }
        };
        /**
         * Switch audio to normal speakers.
         */
        AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
            var scene = this.scene;
            this._headphone = false;
            scene.mainSoundTrack.switchPanningModelToEqualPower();
            if (scene.soundTracks) {
                for (var i = 0; i < scene.soundTracks.length; i++) {
                    scene.soundTracks[i].switchPanningModelToEqualPower();
                }
            }
        };
        AudioSceneComponent.prototype._afterRender = function () {
            var scene = this.scene;
            if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
                return;
            }
            var listeningCamera;
            var audioEngine = BABYLON.Engine.audioEngine;
            if (scene.activeCameras.length > 0) {
                listeningCamera = scene.activeCameras[0];
            }
            else {
                listeningCamera = scene.activeCamera;
            }
            if (listeningCamera && audioEngine.audioContext) {
                audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
                // for VR cameras
                if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
                    listeningCamera = listeningCamera.rigCameras[0];
                }
                var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
                var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
                cameraDirection.normalize();
                // To avoid some errors on GearVR
                if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
                    audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
                }
                var i;
                for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
                    var sound = scene.mainSoundTrack.soundCollection[i];
                    if (sound.useCustomAttenuation) {
                        sound.updateDistanceFromListener();
                    }
                }
                if (scene.soundTracks) {
                    for (i = 0; i < scene.soundTracks.length; i++) {
                        for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
                            sound = scene.soundTracks[i].soundCollection[j];
                            if (sound.useCustomAttenuation) {
                                sound.updateDistanceFromListener();
                            }
                        }
                    }
                }
            }
        };
        return AudioSceneComponent;
    }());
    BABYLON.AudioSceneComponent = AudioSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.audioSceneComponent.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This defines an action helpful to play a defined sound on a triggered action.
     */
    var PlaySoundAction = /** @class */ (function (_super) {
        __extends(PlaySoundAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param sound defines the sound to play
         * @param condition defines the trigger related conditions
         */
        function PlaySoundAction(triggerOptions, sound, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this._sound = sound;
            return _this;
        }
        /** @hidden */
        PlaySoundAction.prototype._prepare = function () {
        };
        /**
         * Execute the action and play the sound.
         */
        PlaySoundAction.prototype.execute = function () {
            if (this._sound !== undefined) {
                this._sound.play();
            }
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        PlaySoundAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "PlaySoundAction",
                properties: [{ name: "sound", value: this._sound.name }]
            }, parent);
        };
        return PlaySoundAction;
    }(BABYLON.Action));
    BABYLON.PlaySoundAction = PlaySoundAction;
    /**
     * This defines an action helpful to stop a defined sound on a triggered action.
     */
    var StopSoundAction = /** @class */ (function (_super) {
        __extends(StopSoundAction, _super);
        /**
         * Instantiate the action
         * @param triggerOptions defines the trigger options
         * @param sound defines the sound to stop
         * @param condition defines the trigger related conditions
         */
        function StopSoundAction(triggerOptions, sound, condition) {
            var _this = _super.call(this, triggerOptions, condition) || this;
            _this._sound = sound;
            return _this;
        }
        /** @hidden */
        StopSoundAction.prototype._prepare = function () {
        };
        /**
         * Execute the action and stop the sound.
         */
        StopSoundAction.prototype.execute = function () {
            if (this._sound !== undefined) {
                this._sound.stop();
            }
        };
        /**
         * Serializes the actions and its related information.
         * @param parent defines the object to serialize in
         * @returns the serialized object
         */
        StopSoundAction.prototype.serialize = function (parent) {
            return _super.prototype._serialize.call(this, {
                name: "StopSoundAction",
                properties: [{ name: "sound", value: this._sound.name }]
            }, parent);
        };
        return StopSoundAction;
    }(BABYLON.Action));
    BABYLON.StopSoundAction = StopSoundAction;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.directAudioActions.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Class for creating a cube texture
     */
    var CubeTexture = /** @class */ (function (_super) {
        __extends(CubeTexture, _super);
        /**
         * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
         * as prefiltered data.
         * @param rootUrl defines the url of the texture or the root name of the six images
         * @param scene defines the scene the texture is attached to
         * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
         * @param noMipmap defines if mipmaps should be created or not
         * @param files defines the six files to load for the different faces
         * @param onLoad defines a callback triggered at the end of the file load if no errors occured
         * @param onError defines a callback triggered in case of error during load
         * @param format defines the internal format to use for the texture once loaded
         * @param prefiltered defines whether or not the texture is created from prefiltered data
         * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
         * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
         * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
         * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
         * @return the cube texture
         */
        function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
            if (extensions === void 0) { extensions = null; }
            if (noMipmap === void 0) { noMipmap = false; }
            if (files === void 0) { files = null; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
            if (prefiltered === void 0) { prefiltered = false; }
            if (forcedExtension === void 0) { forcedExtension = null; }
            if (createPolynomials === void 0) { createPolynomials = false; }
            if (lodScale === void 0) { lodScale = 0.8; }
            if (lodOffset === void 0) { lodOffset = 0; }
            var _this = _super.call(this, scene) || this;
            /**
             * Gets or sets the center of the bounding box associated with the cube texture.
             * It must define where the camera used to render the texture was set
             * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
             */
            _this.boundingBoxPosition = BABYLON.Vector3.Zero();
            _this._rotationY = 0;
            /** @hidden */
            _this._prefiltered = false;
            _this.name = rootUrl;
            _this.url = rootUrl;
            _this._noMipmap = noMipmap;
            _this.hasAlpha = false;
            _this._format = format;
            _this.isCube = true;
            _this._textureMatrix = BABYLON.Matrix.Identity();
            _this._createPolynomials = createPolynomials;
            _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
            if (!rootUrl && !files) {
                return _this;
            }
            var lastDot = rootUrl.lastIndexOf(".");
            var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
            var isDDS = (extension === ".dds");
            var isEnv = (extension === ".env");
            if (isEnv) {
                _this.gammaSpace = false;
                _this._prefiltered = false;
            }
            else {
                _this._prefiltered = prefiltered;
                if (prefiltered) {
                    _this.gammaSpace = false;
                }
            }
            _this._texture = _this._getFromCache(rootUrl, noMipmap);
            if (!files) {
                if (!isEnv && !isDDS && !extensions) {
                    extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
                }
                files = [];
                if (extensions) {
                    for (var index = 0; index < extensions.length; index++) {
                        files.push(rootUrl + extensions[index]);
                    }
                }
            }
            _this._files = files;
            if (!_this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    if (prefiltered) {
                        _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
                    }
                    else {
                        _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
                    }
                }
                else {
                    _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                }
            }
            else if (onLoad) {
                if (_this._texture.isReady) {
                    BABYLON.Tools.SetImmediate(function () { return onLoad(); });
                }
                else {
                    _this._texture.onLoadedObservable.add(onLoad);
                }
            }
            return _this;
        }
        Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
            /**
             * Returns the bounding box size
             * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
             */
            get: function () {
                return this._boundingBoxSize;
            },
            /**
             * Gets or sets the size of the bounding box associated with the cube texture
             * When defined, the cubemap will switch to local mode
             * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
             * @example https://www.babylonjs-playground.com/#RNASML
             */
            set: function (value) {
                if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
                    return;
                }
                this._boundingBoxSize = value;
                var scene = this.getScene();
                if (scene) {
                    scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(CubeTexture.prototype, "rotationY", {
            /**
             * Gets texture matrix rotation angle around Y axis radians.
             */
            get: function () {
                return this._rotationY;
            },
            /**
             * Sets texture matrix rotation angle around Y axis in radians.
             */
            set: function (value) {
                this._rotationY = value;
                this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Creates a cube texture from an array of image urls
         * @param files defines an array of image urls
         * @param scene defines the hosting scene
         * @param noMipmap specifies if mip maps are not used
         * @returns a cube texture
         */
        CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
            var rootUrlKey = "";
            files.forEach(function (url) { return rootUrlKey += url; });
            return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
        };
        /**
         * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
         * @param url defines the url of the prefiltered texture
         * @param scene defines the scene the texture is attached to
         * @param forcedExtension defines the extension of the file if different from the url
         * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
         * @return the prefiltered texture
         */
        CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
            if (forcedExtension === void 0) { forcedExtension = null; }
            if (createPolynomials === void 0) { createPolynomials = true; }
            return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
        };
        /**
         * Delays loading of the cube texture
         */
        CubeTexture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, this._noMipmap);
            if (!this._texture) {
                if (this._prefiltered) {
                    this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
                }
                else {
                    this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
                }
            }
        };
        /**
         * Returns the reflection texture matrix
         * @returns the reflection texture matrix
         */
        CubeTexture.prototype.getReflectionTextureMatrix = function () {
            return this._textureMatrix;
        };
        /**
         * Sets the reflection texture matrix
         * @param value Reflection texture matrix
         */
        CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
            this._textureMatrix = value;
        };
        /**
         * Parses text to create a cube texture
         * @param parsedTexture define the serialized text to read from
         * @param scene defines the hosting scene
         * @param rootUrl defines the root url of the cube texture
         * @returns a cube texture
         */
        CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
            var texture = BABYLON.SerializationHelper.Parse(function () {
                var prefiltered = false;
                if (parsedTexture.prefiltered) {
                    prefiltered = parsedTexture.prefiltered;
                }
                return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
            }, parsedTexture, scene);
            // Local Cubemaps
            if (parsedTexture.boundingBoxPosition) {
                texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
            }
            if (parsedTexture.boundingBoxSize) {
                texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
            }
            // Animations
            if (parsedTexture.animations) {
                for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
                    var parsedAnimation = parsedTexture.animations[animationIndex];
                    texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
            }
            return texture;
        };
        /**
         * Makes a clone, or deep copy, of the cube texture
         * @returns a new cube texture
         */
        CubeTexture.prototype.clone = function () {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () {
                var scene = _this.getScene();
                if (!scene) {
                    return _this;
                }
                return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
            }, this);
        };
        __decorate([
            BABYLON.serialize("rotationY")
        ], CubeTexture.prototype, "rotationY", null);
        return CubeTexture;
    }(BABYLON.BaseTexture));
    BABYLON.CubeTexture = CubeTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.cubeTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Raw cube texture where the raw buffers are passed in
     */
    var RawCubeTexture = /** @class */ (function (_super) {
        __extends(RawCubeTexture, _super);
        /**
         * Creates a cube texture where the raw buffers are passed in.
         * @param scene defines the scene the texture is attached to
         * @param data defines the array of data to use to create each face
         * @param size defines the size of the textures
         * @param format defines the format of the data
         * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
         * @param generateMipMaps  defines if the engine should generate the mip levels
         * @param invertY defines if data must be stored with Y axis inverted
         * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
         * @param compression defines the compression used (null by default)
         */
        function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
            if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (generateMipMaps === void 0) { generateMipMaps = false; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (compression === void 0) { compression = null; }
            var _this = _super.call(this, "", scene) || this;
            _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
            return _this;
        }
        /**
         * Updates the raw cube texture.
         * @param data defines the data to store
         * @param format defines the data format
         * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
         * @param invertY defines if data must be stored with Y axis inverted
         * @param compression defines the compression used (null by default)
         * @param level defines which level of the texture to update
         */
        RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
            if (compression === void 0) { compression = null; }
            if (level === void 0) { level = 0; }
            this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
        };
        /**
         * Updates a raw cube texture with RGBD encoded data.
         * @param data defines the array of data [mipmap][face] to use to create each face
         * @param sphericalPolynomial defines the spherical polynomial for irradiance
         * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
         * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
         * @returns a promsie that resolves when the operation is complete
         */
        RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
            if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
            if (lodScale === void 0) { lodScale = 0.8; }
            if (lodOffset === void 0) { lodOffset = 0; }
            return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
        };
        /**
         * Clones the raw cube texture.
         * @return a new cube texture
         */
        RawCubeTexture.prototype.clone = function () {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () {
                var scene = _this.getScene();
                var internalTexture = _this._texture;
                var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
                if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
                    texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
                }
                return texture;
            }, this);
        };
        /** @hidden */
        RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
            internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
            internalTexture._bufferViewArrayArray = data;
            internalTexture._lodGenerationScale = lodScale;
            internalTexture._lodGenerationOffset = lodOffset;
            internalTexture._sphericalPolynomial = sphericalPolynomial;
            return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
                internalTexture.isReady = true;
            });
        };
        return RawCubeTexture;
    }(BABYLON.CubeTexture));
    BABYLON.RawCubeTexture = RawCubeTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.rawCubeTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This Helps creating a texture that will be created from a camera in your scene.
     * It is basically a dynamic texture that could be used to create special effects for instance.
     * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
     */
    var RenderTargetTexture = /** @class */ (function (_super) {
        __extends(RenderTargetTexture, _super);
        /**
         * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
         * or used a shadow, depth texture...
         * @param name The friendly name of the texture
         * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
         * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
         * @param generateMipMaps True if mip maps need to be generated after render.
         * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
         * @param type The type of the buffer in the RTT (int, half float, float...)
         * @param isCube True if a cube texture needs to be created
         * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
         * @param generateDepthBuffer True to generate a depth buffer
         * @param generateStencilBuffer True to generate a stencil buffer
         * @param isMulti True if multiple textures need to be created (Draw Buffers)
         * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
         */
        function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
            if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (isCube === void 0) { isCube = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
            if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
            if (isMulti === void 0) { isMulti = false; }
            if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
            var _this = _super.call(this, null, scene, !generateMipMaps) || this;
            _this.isCube = isCube;
            /**
             * Define if particles should be rendered in your texture.
             */
            _this.renderParticles = true;
            /**
             * Define if sprites should be rendered in your texture.
             */
            _this.renderSprites = false;
            /**
             * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
             */
            _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
            /**
             * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
             */
            _this.ignoreCameraViewport = false;
            /**
            * An event triggered when the texture is unbind.
            */
            _this.onBeforeBindObservable = new BABYLON.Observable();
            /**
            * An event triggered when the texture is unbind.
            */
            _this.onAfterUnbindObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the texture
            */
            _this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the texture
            */
            _this.onAfterRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after the texture clear
            */
            _this.onClearObservable = new BABYLON.Observable();
            _this._currentRefreshId = -1;
            _this._refreshRate = 1;
            _this._samples = 1;
            /**
             * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
             * It must define where the camera used to render the texture is set
             */
            _this.boundingBoxPosition = BABYLON.Vector3.Zero();
            scene = _this.getScene();
            if (!scene) {
                return _this;
            }
            _this.renderList = new Array();
            _this._engine = scene.getEngine();
            _this.name = name;
            _this.isRenderTarget = true;
            _this._initialSizeParameter = size;
            _this._processSizeParameter(size);
            _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
            });
            _this._generateMipMaps = generateMipMaps ? true : false;
            _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
            // Rendering groups
            _this._renderingManager = new BABYLON.RenderingManager(scene);
            _this._renderingManager._useSceneAutoClearSetup = true;
            if (isMulti) {
                return _this;
            }
            _this._renderTargetOptions = {
                generateMipMaps: generateMipMaps,
                type: type,
                format: format,
                samplingMode: samplingMode,
                generateDepthBuffer: generateDepthBuffer,
                generateStencilBuffer: generateStencilBuffer
            };
            if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
                _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            }
            if (isCube) {
                _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
                _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
                _this._textureMatrix = BABYLON.Matrix.Identity();
            }
            else {
                _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
            }
            return _this;
        }
        Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
            /**
            * Use this list to define the list of mesh you want to render.
            */
            get: function () {
                return this._renderList;
            },
            set: function (value) {
                this._renderList = value;
                if (this._renderList) {
                    this._hookArray(this._renderList);
                }
            },
            enumerable: true,
            configurable: true
        });
        RenderTargetTexture.prototype._hookArray = function (array) {
            var _this = this;
            var oldPush = array.push;
            array.push = function () {
                var items = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    items[_i] = arguments[_i];
                }
                var wasEmpty = array.length === 0;
                var result = oldPush.apply(array, items);
                if (wasEmpty) {
                    _this.getScene().meshes.forEach(function (mesh) {
                        mesh._markSubMeshesAsLightDirty();
                    });
                }
                return result;
            };
            var oldSplice = array.splice;
            array.splice = function (index, deleteCount) {
                var deleted = oldSplice.apply(array, [index, deleteCount]);
                if (array.length === 0) {
                    _this.getScene().meshes.forEach(function (mesh) {
                        mesh._markSubMeshesAsLightDirty();
                    });
                }
                return deleted;
            };
        };
        Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
            /**
             * Set a after unbind callback in the texture.
             * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
             */
            set: function (callback) {
                if (this._onAfterUnbindObserver) {
                    this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
                }
                this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
            /**
             * Set a before render callback in the texture.
             * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
             */
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
            /**
             * Set a after render callback in the texture.
             * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
             */
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
            /**
             * Set a clear callback in the texture.
             * This has been kept for backward compatibility and use of onClearObservable is recommended.
             */
            set: function (callback) {
                if (this._onClearObserver) {
                    this.onClearObservable.remove(this._onClearObserver);
                }
                this._onClearObserver = this.onClearObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
            /**
             * Gets render target creation options that were used.
             */
            get: function () {
                return this._renderTargetOptions;
            },
            enumerable: true,
            configurable: true
        });
        RenderTargetTexture.prototype._onRatioRescale = function () {
            if (this._sizeRatio) {
                this.resize(this._initialSizeParameter);
            }
        };
        Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
            get: function () {
                return this._boundingBoxSize;
            },
            /**
             * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
             * When defined, the cubemap will switch to local mode
             * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
             * @example https://www.babylonjs-playground.com/#RNASML
             */
            set: function (value) {
                if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
                    return;
                }
                this._boundingBoxSize = value;
                var scene = this.getScene();
                if (scene) {
                    scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Creates a depth stencil texture.
         * This is only available in WebGL 2 or with the depth texture extension available.
         * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
         * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
         * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
         */
        RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
            if (comparisonFunction === void 0) { comparisonFunction = 0; }
            if (bilinearFiltering === void 0) { bilinearFiltering = true; }
            if (generateStencil === void 0) { generateStencil = false; }
            if (!this.getScene()) {
                return;
            }
            var engine = this.getScene().getEngine();
            this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
                bilinearFiltering: bilinearFiltering,
                comparisonFunction: comparisonFunction,
                generateStencil: generateStencil,
                isCube: this.isCube
            });
            engine.setFrameBufferDepthStencilTexture(this);
        };
        RenderTargetTexture.prototype._processSizeParameter = function (size) {
            if (size.ratio) {
                this._sizeRatio = size.ratio;
                this._size = {
                    width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
                    height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
                };
            }
            else {
                this._size = size;
            }
        };
        Object.defineProperty(RenderTargetTexture.prototype, "samples", {
            /**
             * Define the number of samples to use in case of MSAA.
             * It defaults to one meaning no MSAA has been enabled.
             */
            get: function () {
                return this._samples;
            },
            set: function (value) {
                if (this._samples === value) {
                    return;
                }
                var scene = this.getScene();
                if (!scene) {
                    return;
                }
                this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Resets the refresh counter of the texture and start bak from scratch.
         * Could be usefull to regenerate the texture if it is setup to render only once.
         */
        RenderTargetTexture.prototype.resetRefreshCounter = function () {
            this._currentRefreshId = -1;
        };
        Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
            /**
             * Define the refresh rate of the texture or the rendering frequency.
             * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
             */
            get: function () {
                return this._refreshRate;
            },
            set: function (value) {
                this._refreshRate = value;
                this.resetRefreshCounter();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Adds a post process to the render target rendering passes.
         * @param postProcess define the post process to add
         */
        RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
            if (!this._postProcessManager) {
                var scene = this.getScene();
                if (!scene) {
                    return;
                }
                this._postProcessManager = new BABYLON.PostProcessManager(scene);
                this._postProcesses = new Array();
            }
            this._postProcesses.push(postProcess);
            this._postProcesses[0].autoClear = false;
        };
        /**
         * Clear all the post processes attached to the render target
         * @param dispose define if the cleared post processesshould also be disposed (false by default)
         */
        RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
            if (dispose === void 0) { dispose = false; }
            if (!this._postProcesses) {
                return;
            }
            if (dispose) {
                for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
                    var postProcess = _a[_i];
                    postProcess.dispose();
                }
            }
            this._postProcesses = [];
        };
        /**
         * Remove one of the post process from the list of attached post processes to the texture
         * @param postProcess define the post process to remove from the list
         */
        RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
            if (!this._postProcesses) {
                return;
            }
            var index = this._postProcesses.indexOf(postProcess);
            if (index === -1) {
                return;
            }
            this._postProcesses.splice(index, 1);
            if (this._postProcesses.length > 0) {
                this._postProcesses[0].autoClear = false;
            }
        };
        /** @hidden */
        RenderTargetTexture.prototype._shouldRender = function () {
            if (this._currentRefreshId === -1) { // At least render once
                this._currentRefreshId = 1;
                return true;
            }
            if (this.refreshRate === this._currentRefreshId) {
                this._currentRefreshId = 1;
                return true;
            }
            this._currentRefreshId++;
            return false;
        };
        /**
         * Gets the actual render size of the texture.
         * @returns the width of the render size
         */
        RenderTargetTexture.prototype.getRenderSize = function () {
            return this.getRenderWidth();
        };
        /**
         * Gets the actual render width of the texture.
         * @returns the width of the render size
         */
        RenderTargetTexture.prototype.getRenderWidth = function () {
            if (this._size.width) {
                return this._size.width;
            }
            return this._size;
        };
        /**
         * Gets the actual render height of the texture.
         * @returns the height of the render size
         */
        RenderTargetTexture.prototype.getRenderHeight = function () {
            if (this._size.width) {
                return this._size.height;
            }
            return this._size;
        };
        Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
            /**
             * Get if the texture can be rescaled or not.
             */
            get: function () {
                return true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Resize the texture using a ratio.
         * @param ratio the ratio to apply to the texture size in order to compute the new target size
         */
        RenderTargetTexture.prototype.scale = function (ratio) {
            var newSize = this.getRenderSize() * ratio;
            this.resize(newSize);
        };
        /**
         * Get the texture reflection matrix used to rotate/transform the reflection.
         * @returns the reflection matrix
         */
        RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
            if (this.isCube) {
                return this._textureMatrix;
            }
            return _super.prototype.getReflectionTextureMatrix.call(this);
        };
        /**
         * Resize the texture to a new desired size.
         * Be carrefull as it will recreate all the data in the new texture.
         * @param size Define the new size. It can be:
         *   - a number for squared texture,
         *   - an object containing { width: number, height: number }
         *   - or an object containing a ratio { ratio: number }
         */
        RenderTargetTexture.prototype.resize = function (size) {
            this.releaseInternalTexture();
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            this._processSizeParameter(size);
            if (this.isCube) {
                this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
            }
            else {
                this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
            }
        };
        /**
         * Renders all the objects from the render list into the texture.
         * @param useCameraPostProcess Define if camera post processes should be used during the rendering
         * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
         */
        RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
            if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
            if (dumpForDebug === void 0) { dumpForDebug = false; }
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            var engine = scene.getEngine();
            if (this.useCameraPostProcesses !== undefined) {
                useCameraPostProcess = this.useCameraPostProcesses;
            }
            if (this._waitingRenderList) {
                this.renderList = [];
                for (var index = 0; index < this._waitingRenderList.length; index++) {
                    var id = this._waitingRenderList[index];
                    var mesh_1 = scene.getMeshByID(id);
                    if (mesh_1) {
                        this.renderList.push(mesh_1);
                    }
                }
                delete this._waitingRenderList;
            }
            // Is predicate defined?
            if (this.renderListPredicate) {
                if (this.renderList) {
                    this.renderList.splice(0); // Clear previous renderList
                }
                else {
                    this.renderList = [];
                }
                var scene = this.getScene();
                if (!scene) {
                    return;
                }
                var sceneMeshes = scene.meshes;
                for (var index = 0; index < sceneMeshes.length; index++) {
                    var mesh = sceneMeshes[index];
                    if (this.renderListPredicate(mesh)) {
                        this.renderList.push(mesh);
                    }
                }
            }
            this.onBeforeBindObservable.notifyObservers(this);
            // Set custom projection.
            // Needs to be before binding to prevent changing the aspect ratio.
            var camera;
            if (this.activeCamera) {
                camera = this.activeCamera;
                engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
                if (this.activeCamera !== scene.activeCamera) {
                    scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
                }
            }
            else {
                camera = scene.activeCamera;
                if (camera) {
                    engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
                }
            }
            // Prepare renderingManager
            this._renderingManager.reset();
            var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
            var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
            var sceneRenderId = scene.getRenderId();
            for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
                var mesh = currentRenderList[meshIndex];
                if (mesh) {
                    if (!mesh.isReady(this.refreshRate === 0)) {
                        this.resetRefreshCounter();
                        continue;
                    }
                    mesh._preActivateForIntermediateRendering(sceneRenderId);
                    var isMasked = void 0;
                    if (!this.renderList && camera) {
                        isMasked = ((mesh.layerMask & camera.layerMask) === 0);
                    }
                    else {
                        isMasked = false;
                    }
                    if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
                        mesh._activate(sceneRenderId);
                        for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
                            var subMesh = mesh.subMeshes[subIndex];
                            scene._activeIndices.addCount(subMesh.indexCount, false);
                            this._renderingManager.dispatch(subMesh, mesh);
                        }
                    }
                }
            }
            for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
                var particleSystem = scene.particleSystems[particleIndex];
                var emitter = particleSystem.emitter;
                if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
                    continue;
                }
                if (currentRenderList.indexOf(emitter) >= 0) {
                    this._renderingManager.dispatchParticles(particleSystem);
                }
            }
            if (this.isCube) {
                for (var face = 0; face < 6; face++) {
                    this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
                    scene.incrementRenderId();
                    scene.resetCachedMaterial();
                }
            }
            else {
                this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
            }
            this.onAfterUnbindObservable.notifyObservers(this);
            if (scene.activeCamera) {
                if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
                    scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
                }
                engine.setViewport(scene.activeCamera.viewport);
            }
            scene.resetCachedMaterial();
        };
        RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
            var minimum = 128;
            var x = renderDimension * scale;
            var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
            // Ensure we don't exceed the render dimension (while staying POT)
            return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
        };
        RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
            var _this = this;
            if (!this._texture) {
                return;
            }
            engine.unBindFramebuffer(this._texture, this.isCube, function () {
                _this.onAfterRenderObservable.notifyObservers(faceIndex);
            });
        };
        RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            var engine = scene.getEngine();
            if (!this._texture) {
                return;
            }
            // Bind
            if (this._postProcessManager) {
                this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
            }
            else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
                if (this._texture) {
                    engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
                }
            }
            this.onBeforeRenderObservable.notifyObservers(faceIndex);
            // Clear
            if (this.onClearObservable.hasObservers()) {
                this.onClearObservable.notifyObservers(engine);
            }
            else {
                engine.clear(this.clearColor || scene.clearColor, true, true, true);
            }
            if (!this._doNotChangeAspectRatio) {
                scene.updateTransformMatrix(true);
            }
            // Render
            this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
            if (this._postProcessManager) {
                this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
            }
            else if (useCameraPostProcess) {
                scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
            }
            if (!this._doNotChangeAspectRatio) {
                scene.updateTransformMatrix(true);
            }
            // Dump ?
            if (dumpForDebug) {
                BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
            }
            // Unbind
            if (!this.isCube || faceIndex === 5) {
                if (this.isCube) {
                    if (faceIndex === 5) {
                        engine.generateMipMapsForCubemap(this._texture);
                    }
                }
                this.unbindFrameBuffer(engine, faceIndex);
            }
            else {
                this.onAfterRenderObservable.notifyObservers(faceIndex);
            }
        };
        /**
         * Overrides the default sort function applied in the renderging group to prepare the meshes.
         * This allowed control for front to back rendering or reversly depending of the special needs.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
         * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
         * @param transparentSortCompareFn The transparent queue comparison function use to sort.
         */
        RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
            if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
            if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
            if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
            this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
         *
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         */
        RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
            this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
            this._renderingManager._useSceneAutoClearSetup = false;
        };
        /**
         * Clones the texture.
         * @returns the cloned texture
         */
        RenderTargetTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // RenderTarget Texture
            newTexture.coordinatesMode = this.coordinatesMode;
            if (this.renderList) {
                newTexture.renderList = this.renderList.slice(0);
            }
            return newTexture;
        };
        /**
         * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
         * @returns The JSON representation of the texture
         */
        RenderTargetTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.renderTargetSize = this.getRenderSize();
            serializationObject.renderList = [];
            if (this.renderList) {
                for (var index = 0; index < this.renderList.length; index++) {
                    serializationObject.renderList.push(this.renderList[index].id);
                }
            }
            return serializationObject;
        };
        /**
         *  This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
         */
        RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
            var objBuffer = this.getInternalTexture();
            var scene = this.getScene();
            if (objBuffer && scene) {
                scene.getEngine()._releaseFramebufferObjects(objBuffer);
            }
        };
        /**
         * Dispose the texture and release its associated resources.
         */
        RenderTargetTexture.prototype.dispose = function () {
            if (this._postProcessManager) {
                this._postProcessManager.dispose();
                this._postProcessManager = null;
            }
            this.clearPostProcesses(true);
            if (this._resizeObserver) {
                this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
                this._resizeObserver = null;
            }
            this.renderList = null;
            // Remove from custom render targets
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            var index = scene.customRenderTargets.indexOf(this);
            if (index >= 0) {
                scene.customRenderTargets.splice(index, 1);
            }
            for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
                var camera = _a[_i];
                index = camera.customRenderTargets.indexOf(this);
                if (index >= 0) {
                    camera.customRenderTargets.splice(index, 1);
                }
            }
            _super.prototype.dispose.call(this);
        };
        /** @hidden */
        RenderTargetTexture.prototype._rebuild = function () {
            if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
                this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
            }
            if (this._postProcessManager) {
                this._postProcessManager._rebuild();
            }
        };
        /**
         * Clear the info related to rendering groups preventing retention point in material dispose.
         */
        RenderTargetTexture.prototype.freeRenderingGroups = function () {
            if (this._renderingManager) {
                this._renderingManager.freeRenderingGroups();
            }
        };
        /**
         * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
         */
        RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
        /**
         * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
         */
        RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
        /**
         * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
         * the central point of your effect and can save a lot of performances.
         */
        RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
        return RenderTargetTexture;
    }(BABYLON.Texture));
    BABYLON.RenderTargetTexture = RenderTargetTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.renderTargetTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * A multi render target, like a render target provides the ability to render to a texture.
     * Unlike the render target, it can render to several draw buffers in one draw.
     * This is specially interesting in deferred rendering or for any effects requiring more than
     * just one color from a single pass.
     */
    var MultiRenderTarget = /** @class */ (function (_super) {
        __extends(MultiRenderTarget, _super);
        /**
         * Instantiate a new multi render target texture.
         * A multi render target, like a render target provides the ability to render to a texture.
         * Unlike the render target, it can render to several draw buffers in one draw.
         * This is specially interesting in deferred rendering or for any effects requiring more than
         * just one color from a single pass.
         * @param name Define the name of the texture
         * @param size Define the size of the buffers to render to
         * @param count Define the number of target we are rendering into
         * @param scene Define the scene the texture belongs to
         * @param options Define the options used to create the multi render target
         */
        function MultiRenderTarget(name, size, count, scene, options) {
            var _this = this;
            var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
            var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
            var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
            _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
            _this._engine = scene.getEngine();
            if (!_this.isSupported) {
                _this.dispose();
                return;
            }
            var types = [];
            var samplingModes = [];
            for (var i = 0; i < count; i++) {
                if (options && options.types && options.types[i] !== undefined) {
                    types.push(options.types[i]);
                }
                else {
                    types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
                }
                if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
                    samplingModes.push(options.samplingModes[i]);
                }
                else {
                    samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
                }
            }
            var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
            var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
            _this._size = size;
            _this._multiRenderTargetOptions = {
                samplingModes: samplingModes,
                generateMipMaps: generateMipMaps,
                generateDepthBuffer: generateDepthBuffer,
                generateStencilBuffer: generateStencilBuffer,
                generateDepthTexture: generateDepthTexture,
                types: types,
                textureCount: count
            };
            _this._createInternalTextures();
            _this._createTextures();
            return _this;
        }
        Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
            /**
             * Get if draw buffers are currently supported by the used hardware and browser.
             */
            get: function () {
                return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MultiRenderTarget.prototype, "textures", {
            /**
             * Get the list of textures generated by the multi render target.
             */
            get: function () {
                return this._textures;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
            /**
             * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
             */
            get: function () {
                return this._textures[this._textures.length - 1];
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
            /**
             * Set the wrapping mode on U of all the textures we are rendering to.
             * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
             */
            set: function (wrap) {
                if (this._textures) {
                    for (var i = 0; i < this._textures.length; i++) {
                        this._textures[i].wrapU = wrap;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
            /**
             * Set the wrapping mode on V of all the textures we are rendering to.
             * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
             */
            set: function (wrap) {
                if (this._textures) {
                    for (var i = 0; i < this._textures.length; i++) {
                        this._textures[i].wrapV = wrap;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        MultiRenderTarget.prototype._rebuild = function () {
            this.releaseInternalTextures();
            this._createInternalTextures();
            for (var i = 0; i < this._internalTextures.length; i++) {
                var texture = this._textures[i];
                texture._texture = this._internalTextures[i];
            }
            // Keeps references to frame buffer and stencil/depth buffer
            this._texture = this._internalTextures[0];
        };
        MultiRenderTarget.prototype._createInternalTextures = function () {
            this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
        };
        MultiRenderTarget.prototype._createTextures = function () {
            this._textures = [];
            for (var i = 0; i < this._internalTextures.length; i++) {
                var texture = new BABYLON.Texture(null, this.getScene());
                texture._texture = this._internalTextures[i];
                this._textures.push(texture);
            }
            // Keeps references to frame buffer and stencil/depth buffer
            this._texture = this._internalTextures[0];
        };
        Object.defineProperty(MultiRenderTarget.prototype, "samples", {
            /**
             * Define the number of samples used if MSAA is enabled.
             */
            get: function () {
                return this._samples;
            },
            set: function (value) {
                if (this._samples === value) {
                    return;
                }
                this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Resize all the textures in the multi render target.
         * Be carrefull as it will recreate all the data in the new texture.
         * @param size Define the new size
         */
        MultiRenderTarget.prototype.resize = function (size) {
            this.releaseInternalTextures();
            this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
            this._createInternalTextures();
        };
        MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
            var _this = this;
            engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
                _this.onAfterRenderObservable.notifyObservers(faceIndex);
            });
        };
        /**
         * Dispose the render targets and their associated resources
         */
        MultiRenderTarget.prototype.dispose = function () {
            this.releaseInternalTextures();
            _super.prototype.dispose.call(this);
        };
        /**
         * Release all the underlying texture used as draw buffers.
         */
        MultiRenderTarget.prototype.releaseInternalTextures = function () {
            if (!this._internalTextures) {
                return;
            }
            for (var i = this._internalTextures.length - 1; i >= 0; i--) {
                if (this._internalTextures[i] !== undefined) {
                    this._internalTextures[i].dispose();
                    this._internalTextures.splice(i, 1);
                }
            }
        };
        return MultiRenderTarget;
    }(BABYLON.RenderTargetTexture));
    BABYLON.MultiRenderTarget = MultiRenderTarget;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.multiRenderTarget.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Mirror texture can be used to simulate the view from a mirror in a scene.
     * It will dynamically be rendered every frame to adapt to the camera point of view.
     * You can then easily use it as a reflectionTexture on a flat surface.
     * In case the surface is not a plane, please consider relying on reflection probes.
     * @see https://doc.babylonjs.com/how_to/reflect#mirrors
     */
    var MirrorTexture = /** @class */ (function (_super) {
        __extends(MirrorTexture, _super);
        /**
         * Instantiates a Mirror Texture.
         * Mirror texture can be used to simulate the view from a mirror in a scene.
         * It will dynamically be rendered every frame to adapt to the camera point of view.
         * You can then easily use it as a reflectionTexture on a flat surface.
         * In case the surface is not a plane, please consider relying on reflection probes.
         * @see https://doc.babylonjs.com/how_to/reflect#mirrors
         * @param name
         * @param size
         * @param scene
         * @param generateMipMaps
         * @param type
         * @param samplingMode
         * @param generateDepthBuffer
         */
        function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
            var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
            _this.scene = scene;
            /**
             * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
             * It is possible to directly set the mirrorPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the mirrorPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the reflector as stated in the doc.
             * @see https://doc.babylonjs.com/how_to/reflect#mirrors
             */
            _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
            _this._transformMatrix = BABYLON.Matrix.Zero();
            _this._mirrorMatrix = BABYLON.Matrix.Zero();
            _this._adaptiveBlurKernel = 0;
            _this._blurKernelX = 0;
            _this._blurKernelY = 0;
            _this._blurRatio = 1.0;
            _this.ignoreCameraViewport = true;
            _this._updateGammaSpace();
            _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
                _this._updateGammaSpace;
            });
            _this.onBeforeRenderObservable.add(function () {
                BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
                _this._savedViewMatrix = scene.getViewMatrix();
                _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
                scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
                scene.clipPlane = _this.mirrorPlane;
                scene.getEngine().cullBackFaces = false;
                scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
            });
            _this.onAfterRenderObservable.add(function () {
                scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
                scene.getEngine().cullBackFaces = true;
                scene._mirroredCameraPosition = null;
                delete scene.clipPlane;
            });
            return _this;
        }
        Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
            get: function () {
                return this._blurRatio;
            },
            /**
             * Define the blur ratio used to blur the reflection if needed.
             */
            set: function (value) {
                if (this._blurRatio === value) {
                    return;
                }
                this._blurRatio = value;
                this._preparePostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
            /**
             * Define the adaptive blur kernel used to blur the reflection if needed.
             * This will autocompute the closest best match for the `blurKernel`
             */
            set: function (value) {
                this._adaptiveBlurKernel = value;
                this._autoComputeBlurKernel();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
            /**
             * Define the blur kernel used to blur the reflection if needed.
             * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
             */
            set: function (value) {
                this.blurKernelX = value;
                this.blurKernelY = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
            get: function () {
                return this._blurKernelX;
            },
            /**
             * Define the blur kernel on the X Axis used to blur the reflection if needed.
             * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
             */
            set: function (value) {
                if (this._blurKernelX === value) {
                    return;
                }
                this._blurKernelX = value;
                this._preparePostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
            get: function () {
                return this._blurKernelY;
            },
            /**
             * Define the blur kernel on the Y Axis used to blur the reflection if needed.
             * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
             */
            set: function (value) {
                if (this._blurKernelY === value) {
                    return;
                }
                this._blurKernelY = value;
                this._preparePostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        MirrorTexture.prototype._autoComputeBlurKernel = function () {
            var engine = this.getScene().getEngine();
            var dw = this.getRenderWidth() / engine.getRenderWidth();
            var dh = this.getRenderHeight() / engine.getRenderHeight();
            this.blurKernelX = this._adaptiveBlurKernel * dw;
            this.blurKernelY = this._adaptiveBlurKernel * dh;
        };
        MirrorTexture.prototype._onRatioRescale = function () {
            if (this._sizeRatio) {
                this.resize(this._initialSizeParameter);
                if (!this._adaptiveBlurKernel) {
                    this._preparePostProcesses();
                }
            }
            if (this._adaptiveBlurKernel) {
                this._autoComputeBlurKernel();
            }
        };
        MirrorTexture.prototype._updateGammaSpace = function () {
            this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
        };
        MirrorTexture.prototype._preparePostProcesses = function () {
            this.clearPostProcesses(true);
            if (this._blurKernelX && this._blurKernelY) {
                var engine = this.getScene().getEngine();
                var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
                this._blurX.autoClear = false;
                if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
                    this._blurX.inputTexture = this._texture;
                }
                else {
                    this._blurX.alwaysForcePOT = true;
                }
                this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
                this._blurY.autoClear = false;
                this._blurY.alwaysForcePOT = this._blurRatio !== 1;
                this.addPostProcess(this._blurX);
                this.addPostProcess(this._blurY);
            }
            else {
                if (this._blurY) {
                    this.removePostProcess(this._blurY);
                    this._blurY.dispose();
                    this._blurY = null;
                }
                if (this._blurX) {
                    this.removePostProcess(this._blurX);
                    this._blurX.dispose();
                    this._blurX = null;
                }
            }
        };
        /**
         * Clone the mirror texture.
         * @returns the cloned texture
         */
        MirrorTexture.prototype.clone = function () {
            var scene = this.getScene();
            if (!scene) {
                return this;
            }
            var textureSize = this.getSize();
            var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // Mirror Texture
            newTexture.mirrorPlane = this.mirrorPlane.clone();
            if (this.renderList) {
                newTexture.renderList = this.renderList.slice(0);
            }
            return newTexture;
        };
        /**
         * Serialize the texture to a JSON representation you could use in Parse later on
         * @returns the serialized JSON representation
         */
        MirrorTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.mirrorPlane = this.mirrorPlane.asArray();
            return serializationObject;
        };
        /**
         * Dispose the texture and release its associated resources.
         */
        MirrorTexture.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
        };
        return MirrorTexture;
    }(BABYLON.RenderTargetTexture));
    BABYLON.MirrorTexture = MirrorTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.mirrorTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Creates a refraction texture used by refraction channel of the standard material.
     * It is like a mirror but to see through a material.
     * @see https://doc.babylonjs.com/how_to/reflect#refraction
     */
    var RefractionTexture = /** @class */ (function (_super) {
        __extends(RefractionTexture, _super);
        /**
         * Creates a refraction texture used by refraction channel of the standard material.
         * It is like a mirror but to see through a material.
         * @see https://doc.babylonjs.com/how_to/reflect#refraction
         * @param name Define the texture name
         * @param size Define the size of the underlying texture
         * @param scene Define the scene the refraction belongs to
         * @param generateMipMaps Define if we need to generate mips level for the refraction
         */
        function RefractionTexture(name, size, scene, generateMipMaps) {
            var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
            /**
             * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
             * It is possible to directly set the refractionPlane by directly using a BABYLON.Plane(a, b, c, d) where a, b and c give the plane normal vector (a, b, c) and d is a scalar displacement from the refractionPlane to the origin. However in all but the very simplest of situations it is more straight forward to set it to the refractor as stated in the doc.
             * @see https://doc.babylonjs.com/how_to/reflect#refraction
             */
            _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
            /**
             * Define how deep under the surface we should see.
             */
            _this.depth = 2.0;
            _this.onBeforeRenderObservable.add(function () {
                scene.clipPlane = _this.refractionPlane;
            });
            _this.onAfterRenderObservable.add(function () {
                delete scene.clipPlane;
            });
            return _this;
        }
        /**
         * Clone the refraction texture.
         * @returns the cloned texture
         */
        RefractionTexture.prototype.clone = function () {
            var scene = this.getScene();
            if (!scene) {
                return this;
            }
            var textureSize = this.getSize();
            var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // Refraction Texture
            newTexture.refractionPlane = this.refractionPlane.clone();
            if (this.renderList) {
                newTexture.renderList = this.renderList.slice(0);
            }
            newTexture.depth = this.depth;
            return newTexture;
        };
        /**
         * Serialize the texture to a JSON representation you could use in Parse later on
         * @returns the serialized JSON representation
         */
        RefractionTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.mirrorPlane = this.refractionPlane.asArray();
            serializationObject.depth = this.depth;
            return serializationObject;
        };
        return RefractionTexture;
    }(BABYLON.RenderTargetTexture));
    BABYLON.RefractionTexture = RefractionTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.refractionTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * A class extending Texture allowing drawing on a texture
     * @see http://doc.babylonjs.com/how_to/dynamictexture
     */
    var DynamicTexture = /** @class */ (function (_super) {
        __extends(DynamicTexture, _super);
        /**
         * Creates a DynamicTexture
         * @param name defines the name of the texture
         * @param options provides 3 alternatives for width and height of texture, a canvas, object with width and height properties, number for both width and height
         * @param scene defines the scene where you want the texture
         * @param generateMipMaps defines the use of MinMaps or not (default is false)
         * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
         * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
         */
        function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
            if (scene === void 0) { scene = null; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
            var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
            _this.name = name;
            _this._engine = _this.getScene().getEngine();
            _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            _this._generateMipMaps = generateMipMaps;
            if (options.getContext) {
                _this._canvas = options;
                _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
            }
            else {
                _this._canvas = document.createElement("canvas");
                if (options.width || options.width === 0) {
                    _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
                }
                else {
                    _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
                }
            }
            var textureSize = _this.getSize();
            _this._canvas.width = textureSize.width;
            _this._canvas.height = textureSize.height;
            _this._context = _this._canvas.getContext("2d");
            return _this;
        }
        Object.defineProperty(DynamicTexture.prototype, "canRescale", {
            /**
             * Gets the current state of canRescale
             */
            get: function () {
                return true;
            },
            enumerable: true,
            configurable: true
        });
        DynamicTexture.prototype._recreate = function (textureSize) {
            this._canvas.width = textureSize.width;
            this._canvas.height = textureSize.height;
            this.releaseInternalTexture();
            this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
        };
        /**
         * Scales the texture
         * @param ratio the scale factor to apply to both width and height
         */
        DynamicTexture.prototype.scale = function (ratio) {
            var textureSize = this.getSize();
            textureSize.width *= ratio;
            textureSize.height *= ratio;
            this._recreate(textureSize);
        };
        /**
         * Resizes the texture
         * @param width the new width
         * @param height the new height
         */
        DynamicTexture.prototype.scaleTo = function (width, height) {
            var textureSize = this.getSize();
            textureSize.width = width;
            textureSize.height = height;
            this._recreate(textureSize);
        };
        /**
         * Gets the context of the canvas used by the texture
         * @returns the canvas context of the dynamic texture
         */
        DynamicTexture.prototype.getContext = function () {
            return this._context;
        };
        /**
         * Clears the texture
         */
        DynamicTexture.prototype.clear = function () {
            var size = this.getSize();
            this._context.fillRect(0, 0, size.width, size.height);
        };
        /**
         * Updates the texture
         * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
         * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
         */
        DynamicTexture.prototype.update = function (invertY, premulAlpha) {
            if (premulAlpha === void 0) { premulAlpha = false; }
            this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
        };
        /**
         * Draws text onto the texture
         * @param text defines the text to be drawn
         * @param x defines the placement of the text from the left
         * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
         * @param font defines the font to be used with font-style, font-size, font-name
         * @param color defines the color used for the text
         * @param clearColor defines the color for the canvas, use null to not overwrite canvas
         * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
         * @param update defines whether texture is immediately update (default is true)
         */
        DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
            if (update === void 0) { update = true; }
            var size = this.getSize();
            if (clearColor) {
                this._context.fillStyle = clearColor;
                this._context.fillRect(0, 0, size.width, size.height);
            }
            this._context.font = font;
            if (x === null || x === undefined) {
                var textSize = this._context.measureText(text);
                x = (size.width - textSize.width) / 2;
            }
            if (y === null || y === undefined) {
                var fontSize = parseInt((font.replace(/\D/g, '')));
                y = (size.height / 2) + (fontSize / 3.65);
            }
            this._context.fillStyle = color;
            this._context.fillText(text, x, y);
            if (update) {
                this.update(invertY);
            }
        };
        /**
         * Clones the texture
         * @returns the clone of the texture.
         */
        DynamicTexture.prototype.clone = function () {
            var scene = this.getScene();
            if (!scene) {
                return this;
            }
            var textureSize = this.getSize();
            var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // Dynamic Texture
            newTexture.wrapU = this.wrapU;
            newTexture.wrapV = this.wrapV;
            return newTexture;
        };
        /**
         * Serializes the dynamic texture.  The scene should be ready before the dynamic texture is serialized
         * @returns a serialized dynamic texture object
         */
        DynamicTexture.prototype.serialize = function () {
            var scene = this.getScene();
            if (scene && !scene.isReady()) {
                BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
            }
            var serializationObject = _super.prototype.serialize.call(this);
            serializationObject.base64String = this._canvas.toDataURL();
            serializationObject.invertY = this._invertY;
            serializationObject.samplingMode = this.samplingMode;
            return serializationObject;
        };
        /** @hidden */
        DynamicTexture.prototype._rebuild = function () {
            this.update();
        };
        return DynamicTexture;
    }(BABYLON.Texture));
    BABYLON.DynamicTexture = DynamicTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.dynamicTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * If you want to display a video in your scene, this is the special texture for that.
     * This special texture works similar to other textures, with the exception of a few parameters.
     * @see https://doc.babylonjs.com/how_to/video_texture
     */
    var VideoTexture = /** @class */ (function (_super) {
        __extends(VideoTexture, _super);
        /**
         * Creates a video texture.
         * If you want to display a video in your scene, this is the special texture for that.
         * This special texture works similar to other textures, with the exception of a few parameters.
         * @see https://doc.babylonjs.com/how_to/video_texture
         * @param name optional name, will detect from video source, if not defined
         * @param src can be used to provide an url, array of urls or an already setup HTML video element.
         * @param scene is obviously the current scene.
         * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
         * @param invertY is false by default but can be used to invert video on Y axis
         * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
         * @param settings allows finer control over video usage
         */
        function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
            if (generateMipMaps === void 0) { generateMipMaps = false; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (settings === void 0) { settings = {
                autoPlay: true,
                loop: true,
                autoUpdateTexture: true,
            }; }
            var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
            _this._onUserActionRequestedObservable = null;
            _this._stillImageCaptured = false;
            _this._poster = false;
            _this._createInternalTexture = function () {
                if (_this._texture != null) {
                    if (_this._poster) {
                        _this._texture.dispose();
                        _this._poster = false;
                    }
                    else {
                        return;
                    }
                }
                if (!_this._engine.needPOTTextures ||
                    (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
                    _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
                    _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
                }
                else {
                    _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    _this._generateMipMaps = false;
                }
                _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
                if (!_this.video.autoplay) {
                    var oldHandler_1 = _this.video.onplaying;
                    var error_1 = false;
                    _this.video.onplaying = function () {
                        _this.video.onplaying = oldHandler_1;
                        _this._texture.isReady = true;
                        _this._updateInternalTexture();
                        if (!error_1) {
                            _this.video.pause();
                        }
                        if (_this.onLoadObservable.hasObservers()) {
                            _this.onLoadObservable.notifyObservers(_this);
                        }
                    };
                    var playing = _this.video.play();
                    if (playing) {
                        playing.then(function () {
                            // Everything is good.
                        })
                            .catch(function () {
                            error_1 = true;
                            // On Chrome for instance, new policies might prevent playing without user interaction.
                            if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
                                _this._onUserActionRequestedObservable.notifyObservers(_this);
                            }
                        });
                    }
                    else {
                        _this.video.onplaying = oldHandler_1;
                        _this._texture.isReady = true;
                        _this._updateInternalTexture();
                        if (_this.onLoadObservable.hasObservers()) {
                            _this.onLoadObservable.notifyObservers(_this);
                        }
                    }
                }
                else {
                    _this._texture.isReady = true;
                    _this._updateInternalTexture();
                    if (_this.onLoadObservable.hasObservers()) {
                        _this.onLoadObservable.notifyObservers(_this);
                    }
                }
            };
            _this.reset = function () {
                if (_this._texture == null) {
                    return;
                }
                if (!_this._poster) {
                    _this._texture.dispose();
                    _this._texture = null;
                }
            };
            _this._updateInternalTexture = function (e) {
                if (_this._texture == null || !_this._texture.isReady) {
                    return;
                }
                if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
                    return;
                }
                _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
            };
            _this._engine = _this.getScene().getEngine();
            _this._generateMipMaps = generateMipMaps;
            _this._samplingMode = samplingMode;
            _this.autoUpdateTexture = settings.autoUpdateTexture;
            _this.name = name || _this._getName(src);
            _this.video = _this._getVideo(src);
            if (settings.poster) {
                _this.video.poster = settings.poster;
            }
            if (settings.autoPlay !== undefined) {
                _this.video.autoplay = settings.autoPlay;
            }
            if (settings.loop !== undefined) {
                _this.video.loop = settings.loop;
            }
            _this.video.setAttribute("playsinline", "");
            _this.video.addEventListener("canplay", _this._createInternalTexture);
            _this.video.addEventListener("paused", _this._updateInternalTexture);
            _this.video.addEventListener("seeked", _this._updateInternalTexture);
            _this.video.addEventListener("emptied", _this.reset);
            if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
                _this._createInternalTexture();
            }
            if (settings.poster) {
                _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
                _this._poster = true;
            }
            return _this;
        }
        Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
            /**
             * Event triggerd when a dom action is required by the user to play the video.
             * This happens due to recent changes in browser policies preventing video to auto start.
             */
            get: function () {
                if (!this._onUserActionRequestedObservable) {
                    this._onUserActionRequestedObservable = new BABYLON.Observable();
                }
                return this._onUserActionRequestedObservable;
            },
            enumerable: true,
            configurable: true
        });
        VideoTexture.prototype._getName = function (src) {
            if (src instanceof HTMLVideoElement) {
                return src.currentSrc;
            }
            if (typeof src === "object") {
                return src.toString();
            }
            return src;
        };
        VideoTexture.prototype._getVideo = function (src) {
            if (src instanceof HTMLVideoElement) {
                BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
                return src;
            }
            var video = document.createElement("video");
            if (typeof src === "string") {
                BABYLON.Tools.SetCorsBehavior(src, video);
                video.src = src;
            }
            else {
                BABYLON.Tools.SetCorsBehavior(src[0], video);
                src.forEach(function (url) {
                    var source = document.createElement("source");
                    source.src = url;
                    video.appendChild(source);
                });
            }
            return video;
        };
        /**
         * @hidden Internal method to initiate `update`.
         */
        VideoTexture.prototype._rebuild = function () {
            this.update();
        };
        /**
         * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
         */
        VideoTexture.prototype.update = function () {
            if (!this.autoUpdateTexture) {
                // Expecting user to call `updateTexture` manually
                return;
            }
            this.updateTexture(true);
        };
        /**
         * Update Texture in `manual` mode. Does not do anything if not visible or paused.
         * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
         */
        VideoTexture.prototype.updateTexture = function (isVisible) {
            if (!isVisible) {
                return;
            }
            if (this.video.paused && this._stillImageCaptured) {
                return;
            }
            this._stillImageCaptured = true;
            this._updateInternalTexture();
        };
        /**
         * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
         * @param url New url.
         */
        VideoTexture.prototype.updateURL = function (url) {
            this.video.src = url;
        };
        /**
         * Dispose the texture and release its associated resources.
         */
        VideoTexture.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            if (this._onUserActionRequestedObservable) {
                this._onUserActionRequestedObservable.clear();
                this._onUserActionRequestedObservable = null;
            }
            this.video.removeEventListener("canplay", this._createInternalTexture);
            this.video.removeEventListener("paused", this._updateInternalTexture);
            this.video.removeEventListener("seeked", this._updateInternalTexture);
            this.video.removeEventListener("emptied", this.reset);
            this.video.pause();
        };
        /**
         * Creates a video texture straight from your WebCam video feed.
         * @param scene Define the scene the texture should be created in
         * @param onReady Define a callback to triggered once the texture will be ready
         * @param constraints Define the constraints to use to create the web cam feed from WebRTC
         */
        VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
            var video = document.createElement("video");
            video.setAttribute('autoplay', '');
            video.setAttribute('muted', '');
            video.setAttribute('playsinline', '');
            var constraintsDeviceId;
            if (constraints && constraints.deviceId) {
                constraintsDeviceId = {
                    exact: constraints.deviceId,
                };
            }
            window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
            if (navigator.mediaDevices) {
                navigator.mediaDevices.getUserMedia({ video: constraints })
                    .then(function (stream) {
                    if (video.mozSrcObject !== undefined) {
                        // hack for Firefox < 19
                        video.mozSrcObject = stream;
                    }
                    else {
                        video.srcObject = stream;
                    }
                    var onPlaying = function () {
                        if (onReady) {
                            onReady(new VideoTexture("video", video, scene, true, true));
                        }
                        video.removeEventListener("playing", onPlaying);
                    };
                    video.addEventListener("playing", onPlaying);
                    video.play();
                })
                    .catch(function (err) {
                    BABYLON.Tools.Error(err.name);
                });
            }
            else {
                navigator.getUserMedia =
                    navigator.getUserMedia ||
                        navigator.webkitGetUserMedia ||
                        navigator.mozGetUserMedia ||
                        navigator.msGetUserMedia;
                if (navigator.getUserMedia) {
                    navigator.getUserMedia({
                        video: {
                            deviceId: constraintsDeviceId,
                            width: {
                                min: (constraints && constraints.minWidth) || 256,
                                max: (constraints && constraints.maxWidth) || 640,
                            },
                            height: {
                                min: (constraints && constraints.minHeight) || 256,
                                max: (constraints && constraints.maxHeight) || 480,
                            },
                        },
                    }, function (stream) {
                        if (video.mozSrcObject !== undefined) {
                            // hack for Firefox < 19
                            video.mozSrcObject = stream;
                        }
                        else {
                            video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
                        }
                        video.play();
                        if (onReady) {
                            onReady(new VideoTexture("video", video, scene, true, true));
                        }
                    }, function (e) {
                        BABYLON.Tools.Error(e.name);
                    });
                }
            }
        };
        return VideoTexture;
    }(BABYLON.Texture));
    BABYLON.VideoTexture = VideoTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.videoTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Raw texture can help creating a texture directly from an array of data.
     * This can be super useful if you either get the data from an uncompressed source or
     * if you wish to create your texture pixel by pixel.
     */
    var RawTexture = /** @class */ (function (_super) {
        __extends(RawTexture, _super);
        /**
         * Instantiates a new RawTexture.
         * Raw texture can help creating a texture directly from an array of data.
         * This can be super useful if you either get the data from an uncompressed source or
         * if you wish to create your texture pixel by pixel.
         * @param data define the array of data to use to create the texture
         * @param width define the width of the texture
         * @param height define the height of the texture
         * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
         * @param scene  define the scene the texture belongs to
         * @param generateMipMaps define whether mip maps should be generated or not
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
         */
        function RawTexture(data, width, height, 
        /**
         * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
         */
        format, scene, generateMipMaps, invertY, samplingMode, type) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
            _this.format = format;
            _this._engine = scene.getEngine();
            _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
            _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            return _this;
        }
        /**
         * Updates the texture underlying data.
         * @param data Define the new data of the texture
         */
        RawTexture.prototype.update = function (data) {
            this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
        };
        /**
         * Creates a luminance texture from some data.
         * @param data Define the texture data
         * @param width Define the width of the texture
         * @param height Define the height of the texture
         * @param scene Define the scene the texture belongs to
         * @param generateMipMaps Define whether or not to create mip maps for the texture
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @returns the luminance texture
         */
        RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
        };
        /**
         * Creates a luminance alpha texture from some data.
         * @param data Define the texture data
         * @param width Define the width of the texture
         * @param height Define the height of the texture
         * @param scene Define the scene the texture belongs to
         * @param generateMipMaps Define whether or not to create mip maps for the texture
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @returns the luminance alpha texture
         */
        RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
        };
        /**
         * Creates an alpha texture from some data.
         * @param data Define the texture data
         * @param width Define the width of the texture
         * @param height Define the height of the texture
         * @param scene Define the scene the texture belongs to
         * @param generateMipMaps Define whether or not to create mip maps for the texture
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @returns the alpha texture
         */
        RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
        };
        /**
         * Creates a RGB texture from some data.
         * @param data Define the texture data
         * @param width Define the width of the texture
         * @param height Define the height of the texture
         * @param scene Define the scene the texture belongs to
         * @param generateMipMaps Define whether or not to create mip maps for the texture
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
         * @returns the RGB alpha texture
         */
        RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
        };
        /**
         * Creates a RGBA texture from some data.
         * @param data Define the texture data
         * @param width Define the width of the texture
         * @param height Define the height of the texture
         * @param scene Define the scene the texture belongs to
         * @param generateMipMaps Define whether or not to create mip maps for the texture
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
         * @returns the RGBA texture
         */
        RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
        };
        /**
         * Creates a R texture from some data.
         * @param data Define the texture data
         * @param width Define the width of the texture
         * @param height Define the height of the texture
         * @param scene Define the scene the texture belongs to
         * @param generateMipMaps Define whether or not to create mip maps for the texture
         * @param invertY define if the data should be flipped on Y when uploaded to the GPU
         * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
         * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
         * @returns the R texture
         */
        RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
            return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
        };
        return RawTexture;
    }(BABYLON.Texture));
    BABYLON.RawTexture = RawTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.rawTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store 3D textures containing user data
     */
    var RawTexture3D = /** @class */ (function (_super) {
        __extends(RawTexture3D, _super);
        /**
         * Create a new RawTexture3D
         * @param data defines the data of the texture
         * @param width defines the width of the texture
         * @param height defines the height of the texture
         * @param depth defines the depth of the texture
         * @param format defines the texture format to use
         * @param scene defines the hosting scene
         * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
         * @param invertY defines if texture must be stored with Y axis inverted
         * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
         * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
         */
        function RawTexture3D(data, width, height, depth, 
        /** Gets or sets the texture format to use */
        format, scene, generateMipMaps, invertY, samplingMode, textureType) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (invertY === void 0) { invertY = false; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
            _this.format = format;
            _this._engine = scene.getEngine();
            _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
            _this.is3D = true;
            return _this;
        }
        /**
         * Update the texture with new data
         * @param data defines the data to store in the texture
         */
        RawTexture3D.prototype.update = function (data) {
            if (!this._texture) {
                return;
            }
            this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
        };
        return RawTexture3D;
    }(BABYLON.Texture));
    BABYLON.RawTexture3D = RawTexture3D;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.rawTexture3D.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * PostProcessManager is used to manage one or more post processes or post process pipelines
     * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
     */
    var PostProcessManager = /** @class */ (function () {
        /**
         * Creates a new instance PostProcess
         * @param scene The scene that the post process is associated with.
         */
        function PostProcessManager(scene) {
            this._vertexBuffers = {};
            this._scene = scene;
        }
        PostProcessManager.prototype._prepareBuffers = function () {
            if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
                return;
            }
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            this._buildIndexBuffer();
        };
        PostProcessManager.prototype._buildIndexBuffer = function () {
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
        };
        /**
         * Rebuilds the vertex buffers of the manager.
         * @hidden
         */
        PostProcessManager.prototype._rebuild = function () {
            var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (!vb) {
                return;
            }
            vb._rebuild();
            this._buildIndexBuffer();
        };
        // Methods
        /**
         * Prepares a frame to be run through a post process.
         * @param sourceTexture The input texture to the post procesess. (default: null)
         * @param postProcesses An array of post processes to be run. (default: null)
         * @returns True if the post processes were able to be run.
         * @hidden
         */
        PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
            if (sourceTexture === void 0) { sourceTexture = null; }
            if (postProcesses === void 0) { postProcesses = null; }
            var camera = this._scene.activeCamera;
            if (!camera) {
                return false;
            }
            var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
            if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
                return false;
            }
            postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
            return true;
        };
        /**
         * Manually render a set of post processes to a texture.
         * @param postProcesses An array of post processes to be run.
         * @param targetTexture The target texture to render to.
         * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
         * @param faceIndex defines the face to render to if a cubemap is defined as the target
         * @param lodLevel defines which lod of the texture to render to
         */
        PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
            if (targetTexture === void 0) { targetTexture = null; }
            if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lodLevel === void 0) { lodLevel = 0; }
            var engine = this._scene.getEngine();
            for (var index = 0; index < postProcesses.length; index++) {
                if (index < postProcesses.length - 1) {
                    postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
                }
                else {
                    if (targetTexture) {
                        engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
                    }
                    else {
                        engine.restoreDefaultFramebuffer();
                    }
                }
                var pp = postProcesses[index];
                var effect = pp.apply();
                if (effect) {
                    pp.onBeforeRenderObservable.notifyObservers(effect);
                    // VBOs
                    this._prepareBuffers();
                    engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
                    // Draw order
                    engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
                    pp.onAfterRenderObservable.notifyObservers(effect);
                }
            }
            // Restore depth buffer
            engine.setDepthBuffer(true);
            engine.setDepthWrite(true);
        };
        /**
         * Finalize the result of the output of the postprocesses.
         * @param doNotPresent If true the result will not be displayed to the screen.
         * @param targetTexture The target texture to render to.
         * @param faceIndex The index of the face to bind the target texture to.
         * @param postProcesses The array of post processes to render.
         * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
         * @hidden
         */
        PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
            if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
            var camera = this._scene.activeCamera;
            if (!camera) {
                return;
            }
            postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
            if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
                return;
            }
            var engine = this._scene.getEngine();
            for (var index = 0, len = postProcesses.length; index < len; index++) {
                var pp = postProcesses[index];
                if (index < len - 1) {
                    pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
                }
                else {
                    if (targetTexture) {
                        engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
                        pp._outputTexture = targetTexture;
                    }
                    else {
                        engine.restoreDefaultFramebuffer();
                        pp._outputTexture = null;
                    }
                }
                if (doNotPresent) {
                    break;
                }
                var effect = pp.apply();
                if (effect) {
                    pp.onBeforeRenderObservable.notifyObservers(effect);
                    // VBOs
                    this._prepareBuffers();
                    engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
                    // Draw order
                    engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
                    pp.onAfterRenderObservable.notifyObservers(effect);
                }
            }
            // Restore states
            engine.setDepthBuffer(true);
            engine.setDepthWrite(true);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
        };
        /**
         * Disposes of the post process manager.
         */
        PostProcessManager.prototype.dispose = function () {
            var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
        };
        return PostProcessManager;
    }());
    BABYLON.PostProcessManager = PostProcessManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.postProcessManager.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * PostProcess can be used to apply a shader to a texture after it has been rendered
     * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
     */
    var PostProcess = /** @class */ (function () {
        /**
         * Creates a new instance PostProcess
         * @param name The name of the PostProcess.
         * @param fragmentUrl The url of the fragment shader to be used.
         * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
         * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
         * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param defines String of defines that will be set when running the fragment shader. (default: null)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
         * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
         * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
         */
        function PostProcess(
        /** Name of the PostProcess. */
        name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
            if (defines === void 0) { defines = null; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            this.name = name;
            /**
            * Width of the texture to apply the post process on
            */
            this.width = -1;
            /**
            * Height of the texture to apply the post process on
            */
            this.height = -1;
            /**
            * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
            * @hidden
            */
            this._outputTexture = null;
            /**
            * If the buffer needs to be cleared before applying the post process. (default: true)
            * Should be set to false if shader will overwrite all previous pixels.
            */
            this.autoClear = true;
            /**
            * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
            */
            this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
            /**
            * Animations to be used for the post processing
            */
            this.animations = new Array();
            /**
             * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
             * Can only be used on a single postprocess or on the last one of a chain. (default: false)
             */
            this.enablePixelPerfectMode = false;
            /**
             * Force the postprocess to be applied without taking in account viewport
             */
            this.forceFullscreenViewport = true;
            /**
            * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
        *
        * | Value | Type                                | Description |
            * | ----- | ----------------------------------- | ----------- |
            * | 1     | SCALEMODE_FLOOR                     | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
            * | 2     | SCALEMODE_NEAREST                   | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
            * | 3     | SCALEMODE_CEILING                   | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
        *
            */
            this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
            /**
            * Force textures to be a power of two (default: false)
            */
            this.alwaysForcePOT = false;
            this._samples = 1;
            /**
            * Modify the scale of the post process to be the same as the viewport (default: false)
            */
            this.adaptScaleToCurrentViewport = false;
            this._reusable = false;
            /**
            * Smart array of input and output textures for the post process.
            * @hidden
            */
            this._textures = new BABYLON.SmartArray(2);
            /**
            * The index in _textures that corresponds to the output texture.
            * @hidden
            */
            this._currentRenderTextureInd = 0;
            this._scaleRatio = new BABYLON.Vector2(1, 1);
            this._texelSize = BABYLON.Vector2.Zero();
            // Events
            /**
            * An event triggered when the postprocess is activated.
            */
            this.onActivateObservable = new BABYLON.Observable();
            /**
            * An event triggered when the postprocess changes its size.
            */
            this.onSizeChangedObservable = new BABYLON.Observable();
            /**
            * An event triggered when the postprocess applies its effect.
            */
            this.onApplyObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the postprocess
            */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the postprocess
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            if (camera != null) {
                this._camera = camera;
                this._scene = camera.getScene();
                camera.attachPostProcess(this);
                this._engine = this._scene.getEngine();
                this._scene.postProcesses.push(this);
            }
            else if (engine) {
                this._engine = engine;
                this._engine.postProcesses.push(this);
            }
            this._options = options;
            this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
            this._reusable = reusable || false;
            this._textureType = textureType;
            this._samplers = samplers || [];
            this._samplers.push("textureSampler");
            this._fragmentUrl = fragmentUrl;
            this._vertexUrl = vertexUrl;
            this._parameters = parameters || [];
            this._parameters.push("scale");
            this._indexParameters = indexParameters;
            if (!blockCompilation) {
                this.updateEffect(defines);
            }
        }
        Object.defineProperty(PostProcess.prototype, "samples", {
            /**
            * Number of sample textures (default: 1)
            */
            get: function () {
                return this._samples;
            },
            set: function (n) {
                var _this = this;
                this._samples = n;
                this._textures.forEach(function (texture) {
                    if (texture.samples !== _this._samples) {
                        _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
                    }
                });
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onActivate", {
            /**
            * A function that is added to the onActivateObservable
            */
            set: function (callback) {
                if (this._onActivateObserver) {
                    this.onActivateObservable.remove(this._onActivateObserver);
                }
                if (callback) {
                    this._onActivateObserver = this.onActivateObservable.add(callback);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
            /**
            * A function that is added to the onSizeChangedObservable
            */
            set: function (callback) {
                if (this._onSizeChangedObserver) {
                    this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
                }
                this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onApply", {
            /**
            * A function that is added to the onApplyObservable
            */
            set: function (callback) {
                if (this._onApplyObserver) {
                    this.onApplyObservable.remove(this._onApplyObserver);
                }
                this._onApplyObserver = this.onApplyObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
            /**
            * A function that is added to the onBeforeRenderObservable
            */
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "onAfterRender", {
            /**
            * A function that is added to the onAfterRenderObservable
            */
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "inputTexture", {
            /**
            * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will
            * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
            */
            get: function () {
                return this._textures.data[this._currentRenderTextureInd];
            },
            set: function (value) {
                this._forcedOutputTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
        * Gets the camera which post process is applied to.
        * @returns The camera the post process is applied to.
        */
        PostProcess.prototype.getCamera = function () {
            return this._camera;
        };
        Object.defineProperty(PostProcess.prototype, "texelSize", {
            /**
            * Gets the texel size of the postprocess.
            * See https://en.wikipedia.org/wiki/Texel_(graphics)
            */
            get: function () {
                if (this._shareOutputWithPostProcess) {
                    return this._shareOutputWithPostProcess.texelSize;
                }
                if (this._forcedOutputTexture) {
                    this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
                }
                return this._texelSize;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the engine which this post process belongs to.
         * @returns The engine the post process was enabled with.
         */
        PostProcess.prototype.getEngine = function () {
            return this._engine;
        };
        /**
         * The effect that is created when initializing the post process.
         * @returns The created effect corrisponding the the postprocess.
         */
        PostProcess.prototype.getEffect = function () {
            return this._effect;
        };
        /**
         * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
         * @param postProcess The post process to share the output with.
         * @returns This post process.
         */
        PostProcess.prototype.shareOutputWith = function (postProcess) {
            this._disposeTextures();
            this._shareOutputWithPostProcess = postProcess;
            return this;
        };
        /**
         * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
         * This should be called if the post process that shares output with this post process is disabled/disposed.
         */
        PostProcess.prototype.useOwnOutput = function () {
            if (this._textures.length == 0) {
                this._textures = new BABYLON.SmartArray(2);
            }
            this._shareOutputWithPostProcess = null;
        };
        /**
         * Updates the effect with the current post process compile time values and recompiles the shader.
         * @param defines Define statements that should be added at the beginning of the shader. (default: null)
         * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
         * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
         * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
         * @param onCompiled Called when the shader has been compiled.
         * @param onError Called if there is an error when compiling a shader.
         */
        PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
            if (defines === void 0) { defines = null; }
            if (uniforms === void 0) { uniforms = null; }
            if (samplers === void 0) { samplers = null; }
            this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== null ? defines : "", undefined, onCompiled, onError, indexParameters || this._indexParameters);
        };
        /**
         * The post process is reusable if it can be used multiple times within one frame.
         * @returns If the post process is reusable
         */
        PostProcess.prototype.isReusable = function () {
            return this._reusable;
        };
        /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
        PostProcess.prototype.markTextureDirty = function () {
            this.width = -1;
        };
        /**
         * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
         * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous.
         * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
         * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
         * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
         * @returns The target texture that was bound to be written to.
         */
        PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
            var _this = this;
            if (sourceTexture === void 0) { sourceTexture = null; }
            camera = camera || this._camera;
            var scene = camera.getScene();
            var engine = scene.getEngine();
            var maxSize = engine.getCaps().maxTextureSize;
            var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
            var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
            // If rendering to a webvr camera's left or right eye only half the width should be used to avoid resize when rendered to screen
            var webVRCamera = camera.parent;
            if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
                requiredWidth /= 2;
            }
            var desiredWidth = (this._options.width || requiredWidth);
            var desiredHeight = this._options.height || requiredHeight;
            if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
                if (this.adaptScaleToCurrentViewport) {
                    var currentViewport = engine.currentViewport;
                    if (currentViewport) {
                        desiredWidth *= currentViewport.width;
                        desiredHeight *= currentViewport.height;
                    }
                }
                if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
                    if (!this._options.width) {
                        desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
                    }
                    if (!this._options.height) {
                        desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
                    }
                }
                if (this.width !== desiredWidth || this.height !== desiredHeight) {
                    if (this._textures.length > 0) {
                        for (var i = 0; i < this._textures.length; i++) {
                            this._engine._releaseTexture(this._textures.data[i]);
                        }
                        this._textures.reset();
                    }
                    this.width = desiredWidth;
                    this.height = desiredHeight;
                    var textureSize = { width: this.width, height: this.height };
                    var textureOptions = {
                        generateMipMaps: false,
                        generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
                        generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
                        samplingMode: this.renderTargetSamplingMode,
                        type: this._textureType
                    };
                    this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
                    if (this._reusable) {
                        this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
                    }
                    this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
                    this.onSizeChangedObservable.notifyObservers(this);
                }
                this._textures.forEach(function (texture) {
                    if (texture.samples !== _this.samples) {
                        _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
                    }
                });
            }
            var target;
            if (this._shareOutputWithPostProcess) {
                target = this._shareOutputWithPostProcess.inputTexture;
            }
            else if (this._forcedOutputTexture) {
                target = this._forcedOutputTexture;
                this.width = this._forcedOutputTexture.width;
                this.height = this._forcedOutputTexture.height;
            }
            else {
                target = this.inputTexture;
            }
            // Bind the input of this post process to be used as the output of the previous post process.
            if (this.enablePixelPerfectMode) {
                this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
                this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
            }
            else {
                this._scaleRatio.copyFromFloats(1, 1);
                this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
            }
            this.onActivateObservable.notifyObservers(camera);
            // Clear
            if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
                this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
            }
            if (this._reusable) {
                this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
            }
            return target;
        };
        Object.defineProperty(PostProcess.prototype, "isSupported", {
            /**
             * If the post process is supported.
             */
            get: function () {
                return this._effect.isSupported;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PostProcess.prototype, "aspectRatio", {
            /**
             * The aspect ratio of the output texture.
             */
            get: function () {
                if (this._shareOutputWithPostProcess) {
                    return this._shareOutputWithPostProcess.aspectRatio;
                }
                if (this._forcedOutputTexture) {
                    return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
                }
                return this.width / this.height;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get a value indicating if the post-process is ready to be used
         * @returns true if the post-process is ready (shader is compiled)
         */
        PostProcess.prototype.isReady = function () {
            return this._effect && this._effect.isReady();
        };
        /**
         * Binds all textures and uniforms to the shader, this will be run on every pass.
         * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
         */
        PostProcess.prototype.apply = function () {
            // Check
            if (!this._effect || !this._effect.isReady()) {
                return null;
            }
            // States
            this._engine.enableEffect(this._effect);
            this._engine.setState(false);
            this._engine.setDepthBuffer(false);
            this._engine.setDepthWrite(false);
            // Alpha
            this._engine.setAlphaMode(this.alphaMode);
            if (this.alphaConstants) {
                this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
            }
            // Bind the output texture of the preivous post process as the input to this post process.
            var source;
            if (this._shareOutputWithPostProcess) {
                source = this._shareOutputWithPostProcess.inputTexture;
            }
            else if (this._forcedOutputTexture) {
                source = this._forcedOutputTexture;
            }
            else {
                source = this.inputTexture;
            }
            this._effect._bindTexture("textureSampler", source);
            // Parameters
            this._effect.setVector2("scale", this._scaleRatio);
            this.onApplyObservable.notifyObservers(this._effect);
            return this._effect;
        };
        PostProcess.prototype._disposeTextures = function () {
            if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
                return;
            }
            if (this._textures.length > 0) {
                for (var i = 0; i < this._textures.length; i++) {
                    this._engine._releaseTexture(this._textures.data[i]);
                }
            }
            this._textures.dispose();
        };
        /**
         * Disposes the post process.
         * @param camera The camera to dispose the post process on.
         */
        PostProcess.prototype.dispose = function (camera) {
            camera = camera || this._camera;
            this._disposeTextures();
            if (this._scene) {
                var index_1 = this._scene.postProcesses.indexOf(this);
                if (index_1 !== -1) {
                    this._scene.postProcesses.splice(index_1, 1);
                }
            }
            else {
                var index_2 = this._engine.postProcesses.indexOf(this);
                if (index_2 !== -1) {
                    this._engine.postProcesses.splice(index_2, 1);
                }
            }
            if (!camera) {
                return;
            }
            camera.detachPostProcess(this);
            var index = camera._postProcesses.indexOf(this);
            if (index === 0 && camera._postProcesses.length > 0) {
                var firstPostProcess = this._camera._getFirstPostProcess();
                if (firstPostProcess) {
                    firstPostProcess.markTextureDirty();
                }
            }
            this.onActivateObservable.clear();
            this.onAfterRenderObservable.clear();
            this.onApplyObservable.clear();
            this.onBeforeRenderObservable.clear();
            this.onSizeChangedObservable.clear();
        };
        return PostProcess;
    }());
    BABYLON.PostProcess = PostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.postProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * PassPostProcess which produces an output the same as it's input
     */
    var PassPostProcess = /** @class */ (function (_super) {
        __extends(PassPostProcess, _super);
        /**
         * Creates the PassPostProcess
         * @param name The name of the effect.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType The type of texture to be used when performing the post processing.
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (camera === void 0) { camera = null; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
        }
        return PassPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.PassPostProcess = PassPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.passPostProcess.js.map

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var BABYLON;
(function (BABYLON) {
    /**
     * Default implementation IShadowGenerator.
     * This is the main object responsible of generating shadows in the framework.
     * Documentation: https://doc.babylonjs.com/babylon101/shadows
     */
    var ShadowGenerator = /** @class */ (function () {
        /**
         * Creates a ShadowGenerator object.
         * A ShadowGenerator is the required tool to use the shadows.
         * Each light casting shadows needs to use its own ShadowGenerator.
         * Documentation : http://doc.babylonjs.com/tutorials/shadows
         * @param mapSize The size of the texture what stores the shadows. Example : 1024.
         * @param light The light object generating the shadows.
         * @param useFullFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
         */
        function ShadowGenerator(mapSize, light, useFullFloatFirst) {
            this._bias = 0.00005;
            this._normalBias = 0;
            this._blurBoxOffset = 1;
            this._blurScale = 2;
            this._blurKernel = 1;
            this._useKernelBlur = false;
            this._filter = ShadowGenerator.FILTER_NONE;
            this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
            this._contactHardeningLightSizeUVRatio = 0.1;
            this._darkness = 0;
            this._transparencyShadow = false;
            /**
             * Controls the extent to which the shadows fade out at the edge of the frustum
             * Used only by directionals and spots
             */
            this.frustumEdgeFalloff = 0;
            /**
             * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
             * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
             * It might on the other hand introduce peter panning.
             */
            this.forceBackFacesOnly = false;
            this._lightDirection = BABYLON.Vector3.Zero();
            this._viewMatrix = BABYLON.Matrix.Zero();
            this._projectionMatrix = BABYLON.Matrix.Zero();
            this._transformMatrix = BABYLON.Matrix.Zero();
            this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            this._currentFaceIndex = 0;
            this._currentFaceIndexCache = 0;
            this._defaultTextureMatrix = BABYLON.Matrix.Identity();
            this._mapSize = mapSize;
            this._light = light;
            this._scene = light.getScene();
            light._shadowGenerator = this;
            var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
            if (!component) {
                component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
                this._scene._addComponent(component);
            }
            // Texture type fallback from float to int if not supported.
            var caps = this._scene.getEngine().getCaps();
            if (!useFullFloatFirst) {
                if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
                    this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                }
                else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
                    this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
                }
                else {
                    this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                }
            }
            else {
                if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
                    this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
                }
                else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
                    this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                }
                else {
                    this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                }
            }
            this._initializeGenerator();
            this._applyFilterValues();
        }
        Object.defineProperty(ShadowGenerator.prototype, "bias", {
            /**
             * Gets the bias: offset applied on the depth preventing acnea (in light direction).
             */
            get: function () {
                return this._bias;
            },
            /**
             * Sets the bias: offset applied on the depth preventing acnea (in light direction).
             */
            set: function (bias) {
                this._bias = bias;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
            /**
             * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
             */
            get: function () {
                return this._normalBias;
            },
            /**
             * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
             */
            set: function (normalBias) {
                this._normalBias = normalBias;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
            /**
             * Gets the blur box offset: offset applied during the blur pass.
             * Only usefull if useKernelBlur = false
             */
            get: function () {
                return this._blurBoxOffset;
            },
            /**
             * Sets the blur box offset: offset applied during the blur pass.
             * Only usefull if useKernelBlur = false
             */
            set: function (value) {
                if (this._blurBoxOffset === value) {
                    return;
                }
                this._blurBoxOffset = value;
                this._disposeBlurPostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
            /**
             * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
             * 2 means half of the size.
             */
            get: function () {
                return this._blurScale;
            },
            /**
             * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
             * 2 means half of the size.
             */
            set: function (value) {
                if (this._blurScale === value) {
                    return;
                }
                this._blurScale = value;
                this._disposeBlurPostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
            /**
             * Gets the blur kernel: kernel size of the blur pass.
             * Only usefull if useKernelBlur = true
             */
            get: function () {
                return this._blurKernel;
            },
            /**
             * Sets the blur kernel: kernel size of the blur pass.
             * Only usefull if useKernelBlur = true
             */
            set: function (value) {
                if (this._blurKernel === value) {
                    return;
                }
                this._blurKernel = value;
                this._disposeBlurPostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
            /**
             * Gets whether the blur pass is a kernel blur (if true) or box blur.
             * Only usefull in filtered mode (useBlurExponentialShadowMap...)
             */
            get: function () {
                return this._useKernelBlur;
            },
            /**
             * Sets whether the blur pass is a kernel blur (if true) or box blur.
             * Only usefull in filtered mode (useBlurExponentialShadowMap...)
             */
            set: function (value) {
                if (this._useKernelBlur === value) {
                    return;
                }
                this._useKernelBlur = value;
                this._disposeBlurPostProcesses();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
            /**
             * Gets the depth scale used in ESM mode.
             */
            get: function () {
                return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
            },
            /**
             * Sets the depth scale used in ESM mode.
             * This can override the scale stored on the light.
             */
            set: function (value) {
                this._depthScale = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "filter", {
            /**
             * Gets the current mode of the shadow generator (normal, PCF, ESM...).
             * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
             */
            get: function () {
                return this._filter;
            },
            /**
             * Sets the current mode of the shadow generator (normal, PCF, ESM...).
             * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
             */
            set: function (value) {
                // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
                if (this._light.needCube()) {
                    if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
                        this.useExponentialShadowMap = true;
                        return;
                    }
                    else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
                        this.useCloseExponentialShadowMap = true;
                        return;
                    }
                    // PCF on cubemap would also be expensive
                    else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
                        this.usePoissonSampling = true;
                        return;
                    }
                }
                // Weblg1 fallback for PCF.
                if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
                    if (this._scene.getEngine().webGLVersion === 1) {
                        this.usePoissonSampling = true;
                        return;
                    }
                }
                if (this._filter === value) {
                    return;
                }
                this._filter = value;
                this._disposeBlurPostProcesses();
                this._applyFilterValues();
                this._light._markMeshesAsLightDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
            /**
             * Gets if the current filter is set to Poisson Sampling.
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
            },
            /**
             * Sets the current filter to Poisson Sampling.
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
            /**
             * Gets if the current filter is set to VSM.
             * DEPRECATED. Should use useExponentialShadowMap instead.
             */
            get: function () {
                BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
                return this.useExponentialShadowMap;
            },
            /**
             * Sets the current filter is to VSM.
             * DEPRECATED. Should use useExponentialShadowMap instead.
             */
            set: function (value) {
                BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
                this.useExponentialShadowMap = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
            /**
             * Gets if the current filter is set to blurred VSM.
             * DEPRECATED. Should use useBlurExponentialShadowMap instead.
             */
            get: function () {
                BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
                return this.useBlurExponentialShadowMap;
            },
            /**
             * Sets the current filter is to blurred VSM.
             * DEPRECATED. Should use useBlurExponentialShadowMap instead.
             */
            set: function (value) {
                BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
                this.useBlurExponentialShadowMap = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
            /**
             * Gets if the current filter is set to ESM.
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
            },
            /**
             * Sets the current filter is to ESM.
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
            /**
             * Gets if the current filter is set to filtered ESM.
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
            },
            /**
             * Gets if the current filter is set to filtered  ESM.
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
            /**
             * Gets if the current filter is set to "close ESM" (using the inverse of the
             * exponential to prevent steep falloff artifacts).
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
            },
            /**
             * Sets the current filter to "close ESM" (using the inverse of the
             * exponential to prevent steep falloff artifacts).
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
            /**
             * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
             * exponential to prevent steep falloff artifacts).
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
            },
            /**
             * Sets the current filter to filtered "close ESM" (using the inverse of the
             * exponential to prevent steep falloff artifacts).
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
            /**
             * Gets if the current filter is set to "PCF" (percentage closer filtering).
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_PCF;
            },
            /**
             * Sets the current filter to "PCF" (percentage closer filtering).
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
            /**
             * Gets the PCF or PCSS Quality.
             * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
             */
            get: function () {
                return this._filteringQuality;
            },
            /**
             * Sets the PCF or PCSS Quality.
             * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
             */
            set: function (filteringQuality) {
                this._filteringQuality = filteringQuality;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
            /**
             * Gets if the current filter is set to "PCSS" (contact hardening).
             */
            get: function () {
                return this.filter === ShadowGenerator.FILTER_PCSS;
            },
            /**
             * Sets the current filter to "PCSS" (contact hardening).
             */
            set: function (value) {
                if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
                    return;
                }
                this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
            /**
             * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
             * Using a ratio helps keeping shape stability independently of the map size.
             *
             * It does not account for the light projection as it was having too much
             * instability during the light setup or during light position changes.
             *
             * Only valid if useContactHardeningShadow is true.
             */
            get: function () {
                return this._contactHardeningLightSizeUVRatio;
            },
            /**
             * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
             * Using a ratio helps keeping shape stability independently of the map size.
             *
             * It does not account for the light projection as it was having too much
             * instability during the light setup or during light position changes.
             *
             * Only valid if useContactHardeningShadow is true.
             */
            set: function (contactHardeningLightSizeUVRatio) {
                this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
         * 0 means strongest and 1 would means no shadow.
         * @returns the darkness.
         */
        ShadowGenerator.prototype.getDarkness = function () {
            return this._darkness;
        };
        /**
         * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
         * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
         * @returns the shadow generator allowing fluent coding.
         */
        ShadowGenerator.prototype.setDarkness = function (darkness) {
            if (darkness >= 1.0) {
                this._darkness = 1.0;
            }
            else if (darkness <= 0.0) {
                this._darkness = 0.0;
            }
            else {
                this._darkness = darkness;
            }
            return this;
        };
        /**
         * Sets the ability to have transparent shadow (boolean).
         * @param transparent True if transparent else False
         * @returns the shadow generator allowing fluent coding
         */
        ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
            this._transparencyShadow = transparent;
            return this;
        };
        /**
         * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
         * @returns The render target texture if present otherwise, null
         */
        ShadowGenerator.prototype.getShadowMap = function () {
            return this._shadowMap;
        };
        /**
         * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
         * @returns The render target texture if the shadow map is present otherwise, null
         */
        ShadowGenerator.prototype.getShadowMapForRendering = function () {
            if (this._shadowMap2) {
                return this._shadowMap2;
            }
            return this._shadowMap;
        };
        /**
         * Helper function to add a mesh and its descendants to the list of shadow casters.
         * @param mesh Mesh to add
         * @param includeDescendants boolean indicating if the descendants should be added. Default to true
         * @returns the Shadow Generator itself
         */
        ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
            if (includeDescendants === void 0) { includeDescendants = true; }
            var _a;
            if (!this._shadowMap) {
                return this;
            }
            if (!this._shadowMap.renderList) {
                this._shadowMap.renderList = [];
            }
            this._shadowMap.renderList.push(mesh);
            if (includeDescendants) {
                (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
            }
            return this;
        };
        /**
         * Helper function to remove a mesh and its descendants from the list of shadow casters
         * @param mesh Mesh to remove
         * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
         * @returns the Shadow Generator itself
         */
        ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
            if (includeDescendants === void 0) { includeDescendants = true; }
            if (!this._shadowMap || !this._shadowMap.renderList) {
                return this;
            }
            var index = this._shadowMap.renderList.indexOf(mesh);
            if (index !== -1) {
                this._shadowMap.renderList.splice(index, 1);
            }
            if (includeDescendants) {
                for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
                    var child = _a[_i];
                    this.removeShadowCaster(child);
                }
            }
            return this;
        };
        /**
         * Returns the associated light object.
         * @returns the light generating the shadow
         */
        ShadowGenerator.prototype.getLight = function () {
            return this._light;
        };
        ShadowGenerator.prototype._initializeGenerator = function () {
            this._light._markMeshesAsLightDirty();
            this._initializeShadowMap();
        };
        ShadowGenerator.prototype._initializeShadowMap = function () {
            var _this = this;
            // Render target
            var engine = this._scene.getEngine();
            if (engine.webGLVersion > 1) {
                this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
                this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
            }
            else {
                this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
            }
            this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._shadowMap.anisotropicFilteringLevel = 1;
            this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._shadowMap.renderParticles = false;
            this._shadowMap.ignoreCameraViewport = true;
            // Record Face Index before render.
            this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
                _this._currentFaceIndex = faceIndex;
                if (_this._filter === ShadowGenerator.FILTER_PCF) {
                    engine.setColorWrite(false);
                }
            });
            // Custom render function.
            this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
            // Blur if required afer render.
            this._shadowMap.onAfterUnbindObservable.add(function () {
                if (_this._filter === ShadowGenerator.FILTER_PCF) {
                    engine.setColorWrite(true);
                }
                if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
                    return;
                }
                var shadowMap = _this.getShadowMapForRendering();
                if (shadowMap) {
                    _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
                }
            });
            // Clear according to the chosen filter.
            var clearZero = new BABYLON.Color4(0, 0, 0, 0);
            var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            this._shadowMap.onClearObservable.add(function (engine) {
                if (_this._filter === ShadowGenerator.FILTER_PCF) {
                    engine.clear(clearOne, false, true, false);
                }
                else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
                    engine.clear(clearZero, true, true, false);
                }
                else {
                    engine.clear(clearOne, true, true, false);
                }
            });
        };
        ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
            var _this = this;
            var engine = this._scene.getEngine();
            var targetSize = this._mapSize / this.blurScale;
            if (!this.useKernelBlur || this.blurScale !== 1.0) {
                this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
                this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            }
            if (this.useKernelBlur) {
                this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
                this._kernelBlurXPostprocess.width = targetSize;
                this._kernelBlurXPostprocess.height = targetSize;
                this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
                    effect.setTexture("textureSampler", _this._shadowMap);
                });
                this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
                this._kernelBlurXPostprocess.autoClear = false;
                this._kernelBlurYPostprocess.autoClear = false;
                if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
                    this._kernelBlurXPostprocess.packedFloat = true;
                    this._kernelBlurYPostprocess.packedFloat = true;
                }
                this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
            }
            else {
                this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
                this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", targetSize, targetSize);
                    effect.setTexture("textureSampler", _this._shadowMap);
                });
                this._boxBlurPostprocess.autoClear = false;
                this._blurPostProcesses = [this._boxBlurPostprocess];
            }
        };
        ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
            var index;
            var engine = this._scene.getEngine();
            if (depthOnlySubMeshes.length) {
                engine.setColorWrite(false);
                for (index = 0; index < depthOnlySubMeshes.length; index++) {
                    this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
                }
                engine.setColorWrite(true);
            }
            for (index = 0; index < opaqueSubMeshes.length; index++) {
                this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
            }
            for (index = 0; index < alphaTestSubMeshes.length; index++) {
                this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
            }
            if (this._transparencyShadow) {
                for (index = 0; index < transparentSubMeshes.length; index++) {
                    this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
                }
            }
        };
        ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
            var _this = this;
            var mesh = subMesh.getRenderingMesh();
            var scene = this._scene;
            var engine = scene.getEngine();
            var material = subMesh.getMaterial();
            if (!material) {
                return;
            }
            // Culling
            engine.setState(material.backFaceCulling);
            // Managing instances
            var batch = mesh._getInstancesRenderList(subMesh._id);
            if (batch.mustReturn) {
                return;
            }
            var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
            if (this.isReady(subMesh, hardwareInstancedRendering)) {
                engine.enableEffect(this._effect);
                mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
                this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
                this._effect.setMatrix("viewProjection", this.getTransformMatrix());
                if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
                    this._effect.setVector3("lightData", this._cachedDirection);
                }
                else {
                    this._effect.setVector3("lightData", this._cachedPosition);
                }
                if (scene.activeCamera) {
                    this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
                }
                // Alpha test
                if (material && material.needAlphaTesting()) {
                    var alphaTexture = material.getAlphaTestTexture();
                    if (alphaTexture) {
                        this._effect.setTexture("diffuseSampler", alphaTexture);
                        this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
                    }
                }
                // Bones
                if (mesh.useBones && mesh.computeBonesUsingShaders) {
                    this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
                }
                // Morph targets
                BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
                if (this.forceBackFacesOnly) {
                    engine.setState(true, 0, false, true);
                }
                // Draw
                mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
                if (this.forceBackFacesOnly) {
                    engine.setState(true, 0, false, false);
                }
            }
            else {
                // Need to reset refresh rate of the shadowMap
                if (this._shadowMap) {
                    this._shadowMap.resetRefreshCounter();
                }
            }
        };
        ShadowGenerator.prototype._applyFilterValues = function () {
            if (!this._shadowMap) {
                return;
            }
            if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
                this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
            }
            else {
                this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            }
        };
        /**
         * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
         * @param onCompiled Callback triggered at the and of the effects compilation
         * @param options Sets of optional options forcing the compilation with different modes
         */
        ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
            var _this = this;
            var localOptions = __assign({ useInstances: false }, options);
            var shadowMap = this.getShadowMap();
            if (!shadowMap) {
                if (onCompiled) {
                    onCompiled(this);
                }
                return;
            }
            var renderList = shadowMap.renderList;
            if (!renderList) {
                if (onCompiled) {
                    onCompiled(this);
                }
                return;
            }
            var subMeshes = new Array();
            for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
                var mesh = renderList_1[_i];
                subMeshes.push.apply(subMeshes, mesh.subMeshes);
            }
            if (subMeshes.length === 0) {
                if (onCompiled) {
                    onCompiled(this);
                }
                return;
            }
            var currentIndex = 0;
            var checkReady = function () {
                if (!_this._scene || !_this._scene.getEngine()) {
                    return;
                }
                while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
                    currentIndex++;
                    if (currentIndex >= subMeshes.length) {
                        if (onCompiled) {
                            onCompiled(_this);
                        }
                        return;
                    }
                }
                setTimeout(checkReady, 16);
            };
            checkReady();
        };
        /**
         * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
         * @param options Sets of optional options forcing the compilation with different modes
         * @returns A promise that resolves when the compilation completes
         */
        ShadowGenerator.prototype.forceCompilationAsync = function (options) {
            var _this = this;
            return new Promise(function (resolve) {
                _this.forceCompilation(function () {
                    resolve();
                }, options);
            });
        };
        /**
         * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
         * @param subMesh The submesh we want to render in the shadow map
         * @param useInstances Defines wether will draw in the map using instances
         * @returns true if ready otherwise, false
         */
        ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
            var defines = [];
            if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
                defines.push("#define FLOAT");
            }
            if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
                defines.push("#define ESM");
            }
            else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
                defines.push("#define DEPTHTEXTURE");
            }
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var mesh = subMesh.getMesh();
            var material = subMesh.getMaterial();
            // Normal bias.
            if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                attribs.push(BABYLON.VertexBuffer.NormalKind);
                defines.push("#define NORMAL");
                if (mesh.nonUniformScaling) {
                    defines.push("#define NONUNIFORMSCALING");
                }
                if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
                    defines.push("#define DIRECTIONINLIGHTDATA");
                }
            }
            // Alpha test
            if (material && material.needAlphaTesting()) {
                var alphaTexture = material.getAlphaTestTexture();
                if (alphaTexture) {
                    defines.push("#define ALPHATEST");
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                        attribs.push(BABYLON.VertexBuffer.UVKind);
                        defines.push("#define UV1");
                    }
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                        if (alphaTexture.coordinatesIndex === 1) {
                            attribs.push(BABYLON.VertexBuffer.UV2Kind);
                            defines.push("#define UV2");
                        }
                    }
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Morph targets
            var manager = mesh.morphTargetManager;
            var morphInfluencers = 0;
            if (manager) {
                if (manager.numInfluencers > 0) {
                    defines.push("#define MORPHTARGETS");
                    morphInfluencers = manager.numInfluencers;
                    defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
                    BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
                }
            }
            // 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", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
            }
            if (!this._effect.isReady()) {
                return false;
            }
            if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
                if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
                    this._initializeBlurRTTAndPostProcesses();
                }
            }
            if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
                return false;
            }
            if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
                return false;
            }
            if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
                return false;
            }
            return true;
        };
        /**
         * Prepare all the defines in a material relying on a shadow map at the specified light index.
         * @param defines Defines of the material we want to update
         * @param lightIndex Index of the light in the enabled light list of the material
         */
        ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
            var scene = this._scene;
            var light = this._light;
            if (!scene.shadowsEnabled || !light.shadowEnabled) {
                return;
            }
            defines["SHADOW" + lightIndex] = true;
            if (this.useContactHardeningShadow) {
                defines["SHADOWPCSS" + lightIndex] = true;
                if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
                    defines["SHADOWLOWQUALITY" + lightIndex] = true;
                }
                else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
                    defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
                }
                // else default to high.
            }
            if (this.usePercentageCloserFiltering) {
                defines["SHADOWPCF" + lightIndex] = true;
                if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
                    defines["SHADOWLOWQUALITY" + lightIndex] = true;
                }
                else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
                    defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
                }
                // else default to high.
            }
            else if (this.usePoissonSampling) {
                defines["SHADOWPOISSON" + lightIndex] = true;
            }
            else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
                defines["SHADOWESM" + lightIndex] = true;
            }
            else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
                defines["SHADOWCLOSEESM" + lightIndex] = true;
            }
            if (light.needCube()) {
                defines["SHADOWCUBE" + lightIndex] = true;
            }
        };
        /**
         * Binds the shadow related information inside of an effect (information like near, far, darkness...
         * defined in the generator but impacting the effect).
         * @param lightIndex Index of the light in the enabled light list of the material owning the effect
         * @param effect The effect we are binfing the information for
         */
        ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
            var light = this._light;
            var scene = this._scene;
            if (!scene.shadowsEnabled || !light.shadowEnabled) {
                return;
            }
            var camera = scene.activeCamera;
            if (!camera) {
                return;
            }
            var shadowMap = this.getShadowMap();
            if (!shadowMap) {
                return;
            }
            if (!light.needCube()) {
                effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
            }
            // Only PCF uses depth stencil texture.
            if (this._filter === ShadowGenerator.FILTER_PCF) {
                effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
                light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
            }
            else if (this._filter === ShadowGenerator.FILTER_PCSS) {
                effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
                effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
                light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
            }
            else {
                effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
                light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
            }
            light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
        };
        /**
         * Gets the transformation matrix used to project the meshes into the map from the light point of view.
         * (eq to shadow prjection matrix * light transform matrix)
         * @returns The transform matrix used to create the shadow map
         */
        ShadowGenerator.prototype.getTransformMatrix = function () {
            var scene = this._scene;
            if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
                return this._transformMatrix;
            }
            this._currentRenderID = scene.getRenderId();
            this._currentFaceIndexCache = this._currentFaceIndex;
            var lightPosition = this._light.position;
            if (this._light.computeTransformedInformation()) {
                lightPosition = this._light.transformedPosition;
            }
            BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
            if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
                this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
            }
            if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
                this._cachedPosition.copyFrom(lightPosition);
                this._cachedDirection.copyFrom(this._lightDirection);
                BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
                var shadowMap = this.getShadowMap();
                if (shadowMap) {
                    var renderList = shadowMap.renderList;
                    if (renderList) {
                        this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
                    }
                }
                this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
            }
            return this._transformMatrix;
        };
        /**
         * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
         * Cube and 2D textures for instance.
         */
        ShadowGenerator.prototype.recreateShadowMap = function () {
            var shadowMap = this._shadowMap;
            if (!shadowMap) {
                return;
            }
            // Track render list.
            var renderList = shadowMap.renderList;
            // Clean up existing data.
            this._disposeRTTandPostProcesses();
            // Reinitializes.
            this._initializeGenerator();
            // Reaffect the filter to ensure a correct fallback if necessary.
            this.filter = this.filter;
            // Reaffect the filter.
            this._applyFilterValues();
            // Reaffect Render List.
            this._shadowMap.renderList = renderList;
        };
        ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
            if (this._shadowMap2) {
                this._shadowMap2.dispose();
                this._shadowMap2 = null;
            }
            if (this._boxBlurPostprocess) {
                this._boxBlurPostprocess.dispose();
                this._boxBlurPostprocess = null;
            }
            if (this._kernelBlurXPostprocess) {
                this._kernelBlurXPostprocess.dispose();
                this._kernelBlurXPostprocess = null;
            }
            if (this._kernelBlurYPostprocess) {
                this._kernelBlurYPostprocess.dispose();
                this._kernelBlurYPostprocess = null;
            }
            this._blurPostProcesses = [];
        };
        ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
            if (this._shadowMap) {
                this._shadowMap.dispose();
                this._shadowMap = null;
            }
            this._disposeBlurPostProcesses();
        };
        /**
         * Disposes the ShadowGenerator.
         * Returns nothing.
         */
        ShadowGenerator.prototype.dispose = function () {
            this._disposeRTTandPostProcesses();
            if (this._light) {
                this._light._shadowGenerator = null;
                this._light._markMeshesAsLightDirty();
            }
        };
        /**
         * Serializes the shadow generator setup to a json object.
         * @returns The serialized JSON object
         */
        ShadowGenerator.prototype.serialize = function () {
            var serializationObject = {};
            var shadowMap = this.getShadowMap();
            if (!shadowMap) {
                return serializationObject;
            }
            serializationObject.lightId = this._light.id;
            serializationObject.mapSize = shadowMap.getRenderSize();
            serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
            serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
            serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
            serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
            serializationObject.usePoissonSampling = this.usePoissonSampling;
            serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
            serializationObject.depthScale = this.depthScale;
            serializationObject.darkness = this.getDarkness();
            serializationObject.blurBoxOffset = this.blurBoxOffset;
            serializationObject.blurKernel = this.blurKernel;
            serializationObject.blurScale = this.blurScale;
            serializationObject.useKernelBlur = this.useKernelBlur;
            serializationObject.transparencyShadow = this._transparencyShadow;
            serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
            serializationObject.bias = this.bias;
            serializationObject.normalBias = this.normalBias;
            serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
            serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
            serializationObject.filteringQuality = this.filteringQuality;
            serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
            serializationObject.renderList = [];
            if (shadowMap.renderList) {
                for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
                    var mesh = shadowMap.renderList[meshIndex];
                    serializationObject.renderList.push(mesh.id);
                }
            }
            return serializationObject;
        };
        /**
         * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
         * @param parsedShadowGenerator The JSON object to parse
         * @param scene The scene to create the shadow map for
         * @returns The parsed shadow generator
         */
        ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
            var light = scene.getLightByID(parsedShadowGenerator.lightId);
            var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
            var shadowMap = shadowGenerator.getShadowMap();
            for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
                var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
                meshes.forEach(function (mesh) {
                    if (!shadowMap) {
                        return;
                    }
                    if (!shadowMap.renderList) {
                        shadowMap.renderList = [];
                    }
                    shadowMap.renderList.push(mesh);
                });
            }
            if (parsedShadowGenerator.usePoissonSampling) {
                shadowGenerator.usePoissonSampling = true;
            }
            else if (parsedShadowGenerator.useExponentialShadowMap) {
                shadowGenerator.useExponentialShadowMap = true;
            }
            else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
                shadowGenerator.useBlurExponentialShadowMap = true;
            }
            else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
                shadowGenerator.useCloseExponentialShadowMap = true;
            }
            else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
                shadowGenerator.useBlurCloseExponentialShadowMap = true;
            }
            else if (parsedShadowGenerator.usePercentageCloserFiltering) {
                shadowGenerator.usePercentageCloserFiltering = true;
            }
            else if (parsedShadowGenerator.useContactHardeningShadow) {
                shadowGenerator.useContactHardeningShadow = true;
            }
            if (parsedShadowGenerator.filteringQuality) {
                shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
            }
            if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
                shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
            }
            // Backward compat
            else if (parsedShadowGenerator.useVarianceShadowMap) {
                shadowGenerator.useExponentialShadowMap = true;
            }
            else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
                shadowGenerator.useBlurExponentialShadowMap = true;
            }
            if (parsedShadowGenerator.depthScale) {
                shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
            }
            if (parsedShadowGenerator.blurScale) {
                shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
            }
            if (parsedShadowGenerator.blurBoxOffset) {
                shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
            }
            if (parsedShadowGenerator.useKernelBlur) {
                shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
            }
            if (parsedShadowGenerator.blurKernel) {
                shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
            }
            if (parsedShadowGenerator.bias !== undefined) {
                shadowGenerator.bias = parsedShadowGenerator.bias;
            }
            if (parsedShadowGenerator.normalBias !== undefined) {
                shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
            }
            if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
                shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
            }
            if (parsedShadowGenerator.darkness) {
                shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
            }
            if (parsedShadowGenerator.transparencyShadow) {
                shadowGenerator.setTransparencyShadow(true);
            }
            shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
            return shadowGenerator;
        };
        /**
         * Shadow generator mode None: no filtering applied.
         */
        ShadowGenerator.FILTER_NONE = 0;
        /**
         * Shadow generator mode ESM: Exponential Shadow Mapping.
         * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
         */
        ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
        /**
         * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
         * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
         */
        ShadowGenerator.FILTER_POISSONSAMPLING = 2;
        /**
         * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
         * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
         */
        ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
        /**
         * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
         * edge artifacts on steep falloff.
         * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
         */
        ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
        /**
         * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
         * edge artifacts on steep falloff.
         * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
         */
        ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
        /**
         * Shadow generator mode PCF: Percentage Closer Filtering
         * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
         * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
         */
        ShadowGenerator.FILTER_PCF = 6;
        /**
         * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
         * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
         * Contact Hardening
         */
        ShadowGenerator.FILTER_PCSS = 7;
        /**
         * Reserved for PCF and PCSS
         * Highest Quality.
         *
         * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
         *
         * Execute PCSS with 32 taps blocker search and 64 taps PCF.
         */
        ShadowGenerator.QUALITY_HIGH = 0;
        /**
         * Reserved for PCF and PCSS
         * Good tradeoff for quality/perf cross devices
         *
         * Execute PCF on a 3*3 kernel.
         *
         * Execute PCSS with 16 taps blocker search and 32 taps PCF.
         */
        ShadowGenerator.QUALITY_MEDIUM = 1;
        /**
         * Reserved for PCF and PCSS
         * The lowest quality but the fastest.
         *
         * Execute PCF on a 1*1 kernel.
         *
         * Execute PCSS with 16 taps blocker search and 16 taps PCF.
         */
        ShadowGenerator.QUALITY_LOW = 2;
        return ShadowGenerator;
    }());
    BABYLON.ShadowGenerator = ShadowGenerator;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.shadowGenerator.js.map

var BABYLON;
(function (BABYLON) {
    // Adds the parser to the scene parsers.
    BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
        // Shadows
        if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
            for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
                var parsedShadowGenerator = parsedData.shadowGenerators[index];
                BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
                // SG would be available on their associated lights
            }
        }
    });
    /**
     * Defines the shadow generator component responsible to manage any shadow generators
     * in a given scene.
     */
    var ShadowGeneratorSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function ShadowGeneratorSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
            this.scene = scene;
        }
        /**
         * Registers the component in a given scene
         */
        ShadowGeneratorSceneComponent.prototype.register = function () {
            this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        ShadowGeneratorSceneComponent.prototype.rebuild = function () {
            // Nothing To Do Here.
        };
        /**
         * Serializes the component data to the specified json object
         * @param serializationObject The object to serialize to
         */
        ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
            // Shadows
            serializationObject.shadowGenerators = [];
            var lights = this.scene.lights;
            for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
                var light = lights_1[_i];
                var shadowGenerator = light.getShadowGenerator();
                if (shadowGenerator) {
                    serializationObject.shadowGenerators.push(shadowGenerator.serialize());
                }
            }
        };
        /**
         * Adds all the element from the container to the scene
         * @param container the container holding the elements
         */
        ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
            // Nothing To Do Here. (directly attached to a light)
        };
        /**
         * Removes all the elements in the container from the scene
         * @param container contains the elements to remove
         */
        ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
            // Nothing To Do Here. (directly attached to a light)
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        ShadowGeneratorSceneComponent.prototype.dispose = function () {
            // Nothing To Do Here.
        };
        ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
            // Shadows
            var scene = this.scene;
            if (this.scene.shadowsEnabled) {
                for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
                    var light = scene.lights[lightIndex];
                    var shadowGenerator = light.getShadowGenerator();
                    if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
                        var shadowMap = (shadowGenerator.getShadowMap());
                        if (scene.textures.indexOf(shadowMap) !== -1) {
                            renderTargets.push(shadowMap);
                        }
                    }
                }
            }
        };
        return ShadowGeneratorSceneComponent;
    }());
    BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used for the default loading screen
     * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
     */
    var DefaultLoadingScreen = /** @class */ (function () {
        /**
         * Creates a new default loading screen
         * @param _renderingCanvas defines the canvas used to render the scene
         * @param _loadingText defines the default text to display
         * @param _loadingDivBackgroundColor defines the default background color
         */
        function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
            if (_loadingText === void 0) { _loadingText = ""; }
            if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
            var _this = this;
            this._renderingCanvas = _renderingCanvas;
            this._loadingText = _loadingText;
            this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
            // Resize
            this._resizeLoadingUI = function () {
                var canvasRect = _this._renderingCanvas.getBoundingClientRect();
                var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
                if (!_this._loadingDiv) {
                    return;
                }
                _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
                _this._loadingDiv.style.left = canvasRect.left + "px";
                _this._loadingDiv.style.top = canvasRect.top + "px";
                _this._loadingDiv.style.width = canvasRect.width + "px";
                _this._loadingDiv.style.height = canvasRect.height + "px";
            };
        }
        /**
         * Function called to display the loading screen
         */
        DefaultLoadingScreen.prototype.displayLoadingUI = function () {
            if (this._loadingDiv) {
                // Do not add a loading screen if there is already one
                return;
            }
            this._loadingDiv = document.createElement("div");
            this._loadingDiv.id = "babylonjsLoadingDiv";
            this._loadingDiv.style.opacity = "0";
            this._loadingDiv.style.transition = "opacity 1.5s ease";
            this._loadingDiv.style.pointerEvents = "none";
            // Loading text
            this._loadingTextDiv = document.createElement("div");
            this._loadingTextDiv.style.position = "absolute";
            this._loadingTextDiv.style.left = "0";
            this._loadingTextDiv.style.top = "50%";
            this._loadingTextDiv.style.marginTop = "80px";
            this._loadingTextDiv.style.width = "100%";
            this._loadingTextDiv.style.height = "20px";
            this._loadingTextDiv.style.fontFamily = "Arial";
            this._loadingTextDiv.style.fontSize = "14px";
            this._loadingTextDiv.style.color = "white";
            this._loadingTextDiv.style.textAlign = "center";
            this._loadingTextDiv.innerHTML = "Loading";
            this._loadingDiv.appendChild(this._loadingTextDiv);
            //set the predefined text
            this._loadingTextDiv.innerHTML = this._loadingText;
            // Generating keyframes
            var style = document.createElement('style');
            style.type = 'text/css';
            var keyFrames = "@-webkit-keyframes spin1 {                    0% { -webkit-transform: rotate(0deg);}\n                    100% { -webkit-transform: rotate(360deg);}\n                }                @keyframes spin1 {                    0% { transform: rotate(0deg);}\n                    100% { transform: rotate(360deg);}\n                }";
            style.innerHTML = keyFrames;
            document.getElementsByTagName('head')[0].appendChild(style);
            // Loading img
            var imgBack = new Image();
            imgBack.src = "data:image/png;base64, ";
            imgBack.style.position = "absolute";
            imgBack.style.left = "50%";
            imgBack.style.top = "50%";
            imgBack.style.marginLeft = "-60px";
            imgBack.style.marginTop = "-60px";
            imgBack.style.animation = "spin1 2s infinite ease-in-out";
            imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
            imgBack.style.transformOrigin = "50% 50%";
            imgBack.style.webkitTransformOrigin = "50% 50%";
            this._loadingDiv.appendChild(imgBack);
            this._resizeLoadingUI();
            window.addEventListener("resize", this._resizeLoadingUI);
            this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
            document.body.appendChild(this._loadingDiv);
            this._loadingDiv.style.opacity = "1";
        };
        /**
         * Function called to hide the loading screen
         */
        DefaultLoadingScreen.prototype.hideLoadingUI = function () {
            var _this = this;
            if (!this._loadingDiv) {
                return;
            }
            var onTransitionEnd = function () {
                if (!_this._loadingDiv) {
                    return;
                }
                document.body.removeChild(_this._loadingDiv);
                window.removeEventListener("resize", _this._resizeLoadingUI);
                _this._loadingDiv = null;
            };
            this._loadingDiv.style.opacity = "0";
            this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
        };
        Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
            get: function () {
                return this._loadingText;
            },
            /**
             * Gets or sets the text to display while loading
             */
            set: function (text) {
                this._loadingText = text;
                if (this._loadingTextDiv) {
                    this._loadingTextDiv.innerHTML = this._loadingText;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
            /**
             * Gets or sets the color to use for the background
             */
            get: function () {
                return this._loadingDivBackgroundColor;
            },
            set: function (color) {
                this._loadingDivBackgroundColor = color;
                if (!this._loadingDiv) {
                    return;
                }
                this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
            },
            enumerable: true,
            configurable: true
        });
        return DefaultLoadingScreen;
    }());
    BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.loadingScreen.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to represent data loading progression
     */
    var SceneLoaderProgressEvent = /** @class */ (function () {
        /**
         * Create a new progress event
         * @param lengthComputable defines if data length to load can be evaluated
         * @param loaded defines the loaded data length
         * @param total defines the data length to load
         */
        function SceneLoaderProgressEvent(
        /** defines if data length to load can be evaluated */
        lengthComputable, 
        /** defines the loaded data length */
        loaded, 
        /** defines the data length to load */
        total) {
            this.lengthComputable = lengthComputable;
            this.loaded = loaded;
            this.total = total;
        }
        /**
         * Creates a new SceneLoaderProgressEvent from a ProgressEvent
         * @param event defines the source event
         * @returns a new SceneLoaderProgressEvent
         */
        SceneLoaderProgressEvent.FromProgressEvent = function (event) {
            return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
        };
        return SceneLoaderProgressEvent;
    }());
    BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
    /**
     * Class used to load scene from various file formats using registered plugins
     * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
     */
    var SceneLoader = /** @class */ (function () {
        function SceneLoader() {
        }
        Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
            /**
             * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
             */
            get: function () {
                return SceneLoader._ForceFullSceneLoadingForIncremental;
            },
            set: function (value) {
                SceneLoader._ForceFullSceneLoadingForIncremental = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
            /**
             * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
             */
            get: function () {
                return SceneLoader._ShowLoadingScreen;
            },
            set: function (value) {
                SceneLoader._ShowLoadingScreen = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "loggingLevel", {
            /**
             * Defines the current logging level (while loading the scene)
             * @ignorenaming
             */
            get: function () {
                return SceneLoader._loggingLevel;
            },
            set: function (value) {
                SceneLoader._loggingLevel = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
            /**
             * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
             */
            get: function () {
                return SceneLoader._CleanBoneMatrixWeights;
            },
            set: function (value) {
                SceneLoader._CleanBoneMatrixWeights = value;
            },
            enumerable: true,
            configurable: true
        });
        SceneLoader._getDefaultPlugin = function () {
            return SceneLoader._registeredPlugins[".babylon"];
        };
        SceneLoader._getPluginForExtension = function (extension) {
            var registeredPlugin = SceneLoader._registeredPlugins[extension];
            if (registeredPlugin) {
                return registeredPlugin;
            }
            BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
            return SceneLoader._getDefaultPlugin();
        };
        SceneLoader._getPluginForDirectLoad = function (data) {
            for (var extension in SceneLoader._registeredPlugins) {
                var plugin = SceneLoader._registeredPlugins[extension].plugin;
                if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
                    return SceneLoader._registeredPlugins[extension];
                }
            }
            return SceneLoader._getDefaultPlugin();
        };
        SceneLoader._getPluginForFilename = function (sceneFilename) {
            var queryStringPosition = sceneFilename.indexOf("?");
            if (queryStringPosition !== -1) {
                sceneFilename = sceneFilename.substring(0, queryStringPosition);
            }
            var dotPosition = sceneFilename.lastIndexOf(".");
            var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
            return SceneLoader._getPluginForExtension(extension);
        };
        // use babylon file loader directly if sceneFilename is prefixed with "data:"
        SceneLoader._getDirectLoad = function (sceneFilename) {
            if (sceneFilename.substr(0, 5) === "data:") {
                return sceneFilename.substr(5);
            }
            return null;
        };
        SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
            var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
            var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
            var plugin;
            if (registeredPlugin.plugin.createPlugin) {
                plugin = registeredPlugin.plugin.createPlugin();
            }
            else {
                plugin = registeredPlugin.plugin;
            }
            var useArrayBuffer = registeredPlugin.isBinary;
            var database;
            SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
            var dataCallback = function (data, responseURL) {
                if (scene.isDisposed) {
                    onError("Scene has been disposed");
                    return;
                }
                scene.database = database;
                onSuccess(plugin, data, responseURL);
            };
            var request = null;
            var pluginDisposed = false;
            var onDisposeObservable = plugin.onDisposeObservable;
            if (onDisposeObservable) {
                onDisposeObservable.add(function () {
                    pluginDisposed = true;
                    if (request) {
                        request.abort();
                        request = null;
                    }
                    onDispose();
                });
            }
            var manifestChecked = function () {
                if (pluginDisposed) {
                    return;
                }
                request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
                    onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
                } : undefined, database, useArrayBuffer, function (request, exception) {
                    onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
                });
            };
            if (directLoad) {
                dataCallback(directLoad);
                return plugin;
            }
            if (fileInfo.rootUrl.indexOf("file:") === -1) {
                var engine = scene.getEngine();
                var canUseOfflineSupport = engine.enableOfflineSupport;
                if (canUseOfflineSupport) {
                    // Also check for exceptions
                    var exceptionFound = false;
                    for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
                        var regex = _a[_i];
                        if (regex.test(fileInfo.url)) {
                            exceptionFound = true;
                            break;
                        }
                    }
                    canUseOfflineSupport = !exceptionFound;
                }
                if (canUseOfflineSupport) {
                    // Checking if a manifest file has been set for this scene and if offline mode has been requested
                    database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
                }
                else {
                    manifestChecked();
                }
            }
            // Loading file from disk via input file or drag'n'drop
            else {
                var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
                if (file) {
                    request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
                }
                else {
                    onError("Unable to find file named " + fileInfo.name);
                }
            }
            return plugin;
        };
        SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
            var url;
            var name;
            if (!sceneFilename) {
                url = rootUrl;
                name = BABYLON.Tools.GetFilename(rootUrl);
                rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
            }
            else {
                if (sceneFilename.substr(0, 1) === "/") {
                    BABYLON.Tools.Error("Wrong sceneFilename parameter");
                    return null;
                }
                url = rootUrl + sceneFilename;
                name = sceneFilename;
            }
            return {
                url: url,
                rootUrl: rootUrl,
                name: name
            };
        };
        // Public functions
        /**
         * Gets a plugin that can load the given extension
         * @param extension defines the extension to load
         * @returns a plugin or null if none works
         */
        SceneLoader.GetPluginForExtension = function (extension) {
            return SceneLoader._getPluginForExtension(extension).plugin;
        };
        /**
         * Gets a boolean indicating that the given extension can be loaded
         * @param extension defines the extension to load
         * @returns true if the extension is supported
         */
        SceneLoader.IsPluginForExtensionAvailable = function (extension) {
            return !!SceneLoader._registeredPlugins[extension];
        };
        /**
         * Adds a new plugin to the list of registered plugins
         * @param plugin defines the plugin to add
         */
        SceneLoader.RegisterPlugin = function (plugin) {
            if (typeof plugin.extensions === "string") {
                var extension = plugin.extensions;
                SceneLoader._registeredPlugins[extension.toLowerCase()] = {
                    plugin: plugin,
                    isBinary: false
                };
            }
            else {
                var extensions = plugin.extensions;
                Object.keys(extensions).forEach(function (extension) {
                    SceneLoader._registeredPlugins[extension.toLowerCase()] = {
                        plugin: plugin,
                        isBinary: extensions[extension].isBinary
                    };
                });
            }
        };
        /**
         * Import meshes into a scene
         * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param scene the instance of BABYLON.Scene to append to
         * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
         * @param onProgress a callback with a progress event for each file being loaded
         * @param onError a callback with the scene, a message, and possibly an exception when import fails
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded plugin
         */
        SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
            if (sceneFilename === void 0) { sceneFilename = ""; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (onSuccess === void 0) { onSuccess = null; }
            if (onProgress === void 0) { onProgress = null; }
            if (onError === void 0) { onError = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            if (!scene) {
                BABYLON.Tools.Error("No scene available to import mesh to");
                return null;
            }
            var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
            if (!fileInfo) {
                return null;
            }
            var loadingToken = {};
            scene._addPendingData(loadingToken);
            var disposeHandler = function () {
                scene._removePendingData(loadingToken);
            };
            var errorHandler = function (message, exception) {
                var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
                if (onError) {
                    onError(scene, errorMessage, exception);
                }
                else {
                    BABYLON.Tools.Error(errorMessage);
                    // should the exception be thrown?
                }
                disposeHandler();
            };
            var progressHandler = onProgress ? function (event) {
                try {
                    onProgress(event);
                }
                catch (e) {
                    errorHandler("Error in onProgress callback", e);
                }
            } : undefined;
            var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
                scene.importedMeshesFiles.push(fileInfo.url);
                if (onSuccess) {
                    try {
                        onSuccess(meshes, particleSystems, skeletons, animationGroups);
                    }
                    catch (e) {
                        errorHandler("Error in onSuccess callback", e);
                    }
                }
                scene._removePendingData(loadingToken);
            };
            return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
                if (plugin.rewriteRootURL) {
                    fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
                }
                if (plugin.importMesh) {
                    var syncedPlugin = plugin;
                    var meshes = new Array();
                    var particleSystems = new Array();
                    var skeletons = new Array();
                    if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
                        return;
                    }
                    scene.loadingPluginName = plugin.name;
                    successHandler(meshes, particleSystems, skeletons, []);
                }
                else {
                    var asyncedPlugin = plugin;
                    asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
                        scene.loadingPluginName = plugin.name;
                        successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
                    }).catch(function (error) {
                        errorHandler(error.message, error);
                    });
                }
            }, progressHandler, errorHandler, disposeHandler, pluginExtension);
        };
        /**
         * Import meshes into a scene
         * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param scene the instance of BABYLON.Scene to append to
         * @param onProgress a callback with a progress event for each file being loaded
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
         */
        SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
            if (sceneFilename === void 0) { sceneFilename = ""; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (onProgress === void 0) { onProgress = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            return new Promise(function (resolve, reject) {
                SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
                    resolve({
                        meshes: meshes,
                        particleSystems: particleSystems,
                        skeletons: skeletons,
                        animationGroups: animationGroups
                    });
                }, onProgress, function (scene, message, exception) {
                    reject(exception || new Error(message));
                }, pluginExtension);
            });
        };
        /**
         * Load a scene
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param engine is the instance of BABYLON.Engine to use to create the scene
         * @param onSuccess a callback with the scene when import succeeds
         * @param onProgress a callback with a progress event for each file being loaded
         * @param onError a callback with the scene, a message, and possibly an exception when import fails
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded plugin
         */
        SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
            if (onSuccess === void 0) { onSuccess = null; }
            if (onProgress === void 0) { onProgress = null; }
            if (onError === void 0) { onError = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
        };
        /**
         * Load a scene
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param engine is the instance of BABYLON.Engine to use to create the scene
         * @param onProgress a callback with a progress event for each file being loaded
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded scene
         */
        SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
            if (onProgress === void 0) { onProgress = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            return new Promise(function (resolve, reject) {
                SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
                    resolve(scene);
                }, onProgress, function (scene, message, exception) {
                    reject(exception || new Error(message));
                }, pluginExtension);
            });
        };
        /**
         * Append a scene
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param scene is the instance of BABYLON.Scene to append to
         * @param onSuccess a callback with the scene when import succeeds
         * @param onProgress a callback with a progress event for each file being loaded
         * @param onError a callback with the scene, a message, and possibly an exception when import fails
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded plugin
         */
        SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
            if (sceneFilename === void 0) { sceneFilename = ""; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (onSuccess === void 0) { onSuccess = null; }
            if (onProgress === void 0) { onProgress = null; }
            if (onError === void 0) { onError = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            if (!scene) {
                BABYLON.Tools.Error("No scene available to append to");
                return null;
            }
            var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
            if (!fileInfo) {
                return null;
            }
            if (SceneLoader.ShowLoadingScreen) {
                scene.getEngine().displayLoadingUI();
            }
            var loadingToken = {};
            scene._addPendingData(loadingToken);
            var disposeHandler = function () {
                scene._removePendingData(loadingToken);
                scene.getEngine().hideLoadingUI();
            };
            var errorHandler = function (message, exception) {
                var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
                if (onError) {
                    onError(scene, errorMessage, exception);
                }
                else {
                    BABYLON.Tools.Error(errorMessage);
                    // should the exception be thrown?
                }
                disposeHandler();
            };
            var progressHandler = onProgress ? function (event) {
                try {
                    onProgress(event);
                }
                catch (e) {
                    errorHandler("Error in onProgress callback", e);
                }
            } : undefined;
            var successHandler = function () {
                if (onSuccess) {
                    try {
                        onSuccess(scene);
                    }
                    catch (e) {
                        errorHandler("Error in onSuccess callback", e);
                    }
                }
                scene._removePendingData(loadingToken);
            };
            return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
                if (plugin.load) {
                    var syncedPlugin = plugin;
                    if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
                        return;
                    }
                    scene.loadingPluginName = plugin.name;
                    successHandler();
                }
                else {
                    var asyncedPlugin = plugin;
                    asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
                        scene.loadingPluginName = plugin.name;
                        successHandler();
                    }).catch(function (error) {
                        errorHandler(error.message, error);
                    });
                }
                if (SceneLoader.ShowLoadingScreen) {
                    scene.executeWhenReady(function () {
                        scene.getEngine().hideLoadingUI();
                    });
                }
            }, progressHandler, errorHandler, disposeHandler, pluginExtension);
        };
        /**
         * Append a scene
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param scene is the instance of BABYLON.Scene to append to
         * @param onProgress a callback with a progress event for each file being loaded
         * @param pluginExtension the extension used to determine the plugin
         * @returns The given scene
         */
        SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
            if (sceneFilename === void 0) { sceneFilename = ""; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (onProgress === void 0) { onProgress = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            return new Promise(function (resolve, reject) {
                SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
                    resolve(scene);
                }, onProgress, function (scene, message, exception) {
                    reject(exception || new Error(message));
                }, pluginExtension);
            });
        };
        /**
         * Load a scene into an asset container
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
         * @param onSuccess a callback with the scene when import succeeds
         * @param onProgress a callback with a progress event for each file being loaded
         * @param onError a callback with the scene, a message, and possibly an exception when import fails
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded plugin
         */
        SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
            if (sceneFilename === void 0) { sceneFilename = ""; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (onSuccess === void 0) { onSuccess = null; }
            if (onProgress === void 0) { onProgress = null; }
            if (onError === void 0) { onError = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            if (!scene) {
                BABYLON.Tools.Error("No scene available to load asset container to");
                return null;
            }
            var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
            if (!fileInfo) {
                return null;
            }
            var loadingToken = {};
            scene._addPendingData(loadingToken);
            var disposeHandler = function () {
                scene._removePendingData(loadingToken);
            };
            var errorHandler = function (message, exception) {
                var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
                if (onError) {
                    onError(scene, errorMessage, exception);
                }
                else {
                    BABYLON.Tools.Error(errorMessage);
                    // should the exception be thrown?
                }
                disposeHandler();
            };
            var progressHandler = onProgress ? function (event) {
                try {
                    onProgress(event);
                }
                catch (e) {
                    errorHandler("Error in onProgress callback", e);
                }
            } : undefined;
            var successHandler = function (assets) {
                if (onSuccess) {
                    try {
                        onSuccess(assets);
                    }
                    catch (e) {
                        errorHandler("Error in onSuccess callback", e);
                    }
                }
                scene._removePendingData(loadingToken);
            };
            return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
                if (plugin.loadAssetContainer) {
                    var syncedPlugin = plugin;
                    var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
                    if (!assetContainer) {
                        return;
                    }
                    scene.loadingPluginName = plugin.name;
                    successHandler(assetContainer);
                }
                else if (plugin.loadAssetContainerAsync) {
                    var asyncedPlugin = plugin;
                    asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
                        scene.loadingPluginName = plugin.name;
                        successHandler(assetContainer);
                    }).catch(function (error) {
                        errorHandler(error.message, error);
                    });
                }
                else {
                    errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
                }
                if (SceneLoader.ShowLoadingScreen) {
                    scene.executeWhenReady(function () {
                        scene.getEngine().hideLoadingUI();
                    });
                }
            }, progressHandler, errorHandler, disposeHandler, pluginExtension);
        };
        /**
         * Load a scene into an asset container
         * @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
         * @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
         * @param scene is the instance of BABYLON.Scene to append to
         * @param onProgress a callback with a progress event for each file being loaded
         * @param pluginExtension the extension used to determine the plugin
         * @returns The loaded asset container
         */
        SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
            if (sceneFilename === void 0) { sceneFilename = ""; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (onProgress === void 0) { onProgress = null; }
            if (pluginExtension === void 0) { pluginExtension = null; }
            return new Promise(function (resolve, reject) {
                SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
                    resolve(assetContainer);
                }, onProgress, function (scene, message, exception) {
                    reject(exception || new Error(message));
                }, pluginExtension);
            });
        };
        // Flags
        SceneLoader._ForceFullSceneLoadingForIncremental = false;
        SceneLoader._ShowLoadingScreen = true;
        SceneLoader._CleanBoneMatrixWeights = false;
        /**
         * No logging while loading
         */
        SceneLoader.NO_LOGGING = 0;
        /**
         * Minimal logging while loading
         */
        SceneLoader.MINIMAL_LOGGING = 1;
        /**
         * Summary logging while loading
         */
        SceneLoader.SUMMARY_LOGGING = 2;
        /**
         * Detailled logging while loading
         */
        SceneLoader.DETAILED_LOGGING = 3;
        SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
        // Members
        /**
         * Event raised when a plugin is used to load a scene
         */
        SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
        SceneLoader._registeredPlugins = {};
        return SceneLoader;
    }());
    BABYLON.SceneLoader = SceneLoader;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sceneLoader.js.map

var BABYLON;
(function (BABYLON) {
    var parseMaterialById = function (id, parsedData, scene, rootUrl) {
        for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
            var parsedMaterial = parsedData.materials[index];
            if (parsedMaterial.id === id) {
                return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
            }
        }
        return null;
    };
    var isDescendantOf = function (mesh, names, hierarchyIds) {
        for (var i in names) {
            if (mesh.name === names[i]) {
                hierarchyIds.push(mesh.id);
                return true;
            }
        }
        if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
            hierarchyIds.push(mesh.id);
            return true;
        }
        return false;
    };
    var logOperation = function (operation, producer) {
        return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
    };
    var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
        if (addToScene === void 0) { addToScene = false; }
        var container = new BABYLON.AssetContainer(scene);
        // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
        // when SceneLoader.debugLogging = true (default), or exception encountered.
        // Everything stored in var log instead of writing separate lines to support only writing in exception,
        // and avoid problems with multiple concurrent .babylon loads.
        var log = "importScene has failed JSON parse";
        try {
            var parsedData = JSON.parse(data);
            log = "";
            var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
            var index;
            var cache;
            // Lights
            if (parsedData.lights !== undefined && parsedData.lights !== null) {
                for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
                    var parsedLight = parsedData.lights[index];
                    var light = BABYLON.Light.Parse(parsedLight, scene);
                    if (light) {
                        container.lights.push(light);
                        log += (index === 0 ? "\n\tLights:" : "");
                        log += "\n\t\t" + light.toString(fullDetails);
                    }
                }
            }
            // Animations
            if (parsedData.animations !== undefined && parsedData.animations !== null) {
                for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
                    var parsedAnimation = parsedData.animations[index];
                    var animation = BABYLON.Animation.Parse(parsedAnimation);
                    scene.animations.push(animation);
                    container.animations.push(animation);
                    log += (index === 0 ? "\n\tAnimations:" : "");
                    log += "\n\t\t" + animation.toString(fullDetails);
                }
            }
            // Materials
            if (parsedData.materials !== undefined && parsedData.materials !== null) {
                for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
                    var parsedMaterial = parsedData.materials[index];
                    var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
                    container.materials.push(mat);
                    log += (index === 0 ? "\n\tMaterials:" : "");
                    log += "\n\t\t" + mat.toString(fullDetails);
                }
            }
            if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
                for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
                    var parsedMultiMaterial = parsedData.multiMaterials[index];
                    var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
                    container.multiMaterials.push(mmat);
                    log += (index === 0 ? "\n\tMultiMaterials:" : "");
                    log += "\n\t\t" + mmat.toString(fullDetails);
                }
            }
            // Morph targets
            if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
                for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
                    var managerData = _a[_i];
                    container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
                }
            }
            // Skeletons
            if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
                for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
                    var parsedSkeleton = parsedData.skeletons[index];
                    var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
                    container.skeletons.push(skeleton);
                    log += (index === 0 ? "\n\tSkeletons:" : "");
                    log += "\n\t\t" + skeleton.toString(fullDetails);
                }
            }
            // Geometries
            var geometries = parsedData.geometries;
            if (geometries !== undefined && geometries !== null) {
                var addedGeometry = new Array();
                // Boxes
                var boxes = geometries.boxes;
                if (boxes !== undefined && boxes !== null) {
                    for (index = 0, cache = boxes.length; index < cache; index++) {
                        var parsedBox = boxes[index];
                        addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
                    }
                }
                // Spheres
                var spheres = geometries.spheres;
                if (spheres !== undefined && spheres !== null) {
                    for (index = 0, cache = spheres.length; index < cache; index++) {
                        var parsedSphere = spheres[index];
                        addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
                    }
                }
                // Cylinders
                var cylinders = geometries.cylinders;
                if (cylinders !== undefined && cylinders !== null) {
                    for (index = 0, cache = cylinders.length; index < cache; index++) {
                        var parsedCylinder = cylinders[index];
                        addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
                    }
                }
                // Toruses
                var toruses = geometries.toruses;
                if (toruses !== undefined && toruses !== null) {
                    for (index = 0, cache = toruses.length; index < cache; index++) {
                        var parsedTorus = toruses[index];
                        addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
                    }
                }
                // Grounds
                var grounds = geometries.grounds;
                if (grounds !== undefined && grounds !== null) {
                    for (index = 0, cache = grounds.length; index < cache; index++) {
                        var parsedGround = grounds[index];
                        addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
                    }
                }
                // Planes
                var planes = geometries.planes;
                if (planes !== undefined && planes !== null) {
                    for (index = 0, cache = planes.length; index < cache; index++) {
                        var parsedPlane = planes[index];
                        addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
                    }
                }
                // TorusKnots
                var torusKnots = geometries.torusKnots;
                if (torusKnots !== undefined && torusKnots !== null) {
                    for (index = 0, cache = torusKnots.length; index < cache; index++) {
                        var parsedTorusKnot = torusKnots[index];
                        addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
                    }
                }
                // VertexData
                var vertexData = geometries.vertexData;
                if (vertexData !== undefined && vertexData !== null) {
                    for (index = 0, cache = vertexData.length; index < cache; index++) {
                        var parsedVertexData = vertexData[index];
                        addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
                    }
                }
                addedGeometry.forEach(function (g) {
                    if (g) {
                        container.geometries.push(g);
                    }
                });
            }
            // Transform nodes
            if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
                for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
                    var parsedTransformNode = parsedData.transformNodes[index];
                    var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
                    container.transformNodes.push(node);
                }
            }
            // Meshes
            if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
                for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
                    var parsedMesh = parsedData.meshes[index];
                    var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
                    container.meshes.push(mesh);
                    log += (index === 0 ? "\n\tMeshes:" : "");
                    log += "\n\t\t" + mesh.toString(fullDetails);
                }
            }
            // Cameras
            if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
                for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
                    var parsedCamera = parsedData.cameras[index];
                    var camera = BABYLON.Camera.Parse(parsedCamera, scene);
                    container.cameras.push(camera);
                    log += (index === 0 ? "\n\tCameras:" : "");
                    log += "\n\t\t" + camera.toString(fullDetails);
                }
            }
            // Animation Groups
            if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
                for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
                    var parsedAnimationGroup = parsedData.animationGroups[index];
                    var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
                    container.animationGroups.push(animationGroup);
                    log += (index === 0 ? "\n\tAnimationGroups:" : "");
                    log += "\n\t\t" + animationGroup.toString(fullDetails);
                }
            }
            // Browsing all the graph to connect the dots
            for (index = 0, cache = scene.cameras.length; index < cache; index++) {
                var camera = scene.cameras[index];
                if (camera._waitingParentId) {
                    camera.parent = scene.getLastEntryByID(camera._waitingParentId);
                    camera._waitingParentId = null;
                }
            }
            for (index = 0, cache = scene.lights.length; index < cache; index++) {
                var light_1 = scene.lights[index];
                if (light_1 && light_1._waitingParentId) {
                    light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
                    light_1._waitingParentId = null;
                }
            }
            // Connect parents & children and parse actions
            for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
                var transformNode = scene.transformNodes[index];
                if (transformNode._waitingParentId) {
                    transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
                    transformNode._waitingParentId = null;
                }
            }
            for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                var mesh = scene.meshes[index];
                if (mesh._waitingParentId) {
                    mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
                    mesh._waitingParentId = null;
                }
            }
            // freeze world matrix application
            for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                var currentMesh = scene.meshes[index];
                if (currentMesh._waitingFreezeWorldMatrix) {
                    currentMesh.freezeWorldMatrix();
                    currentMesh._waitingFreezeWorldMatrix = null;
                }
                else {
                    currentMesh.computeWorldMatrix(true);
                }
            }
            // Lights exclusions / inclusions
            for (index = 0, cache = scene.lights.length; index < cache; index++) {
                var light_2 = scene.lights[index];
                // Excluded check
                if (light_2._excludedMeshesIds.length > 0) {
                    for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
                        var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
                        if (excludedMesh) {
                            light_2.excludedMeshes.push(excludedMesh);
                        }
                    }
                    light_2._excludedMeshesIds = [];
                }
                // Included check
                if (light_2._includedOnlyMeshesIds.length > 0) {
                    for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
                        var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
                        if (includedOnlyMesh) {
                            light_2.includedOnlyMeshes.push(includedOnlyMesh);
                        }
                    }
                    light_2._includedOnlyMeshesIds = [];
                }
            }
            BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
            // Actions (scene) Done last as it can access other objects.
            for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                var mesh = scene.meshes[index];
                if (mesh._waitingActions) {
                    BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
                    mesh._waitingActions = null;
                }
            }
            if (parsedData.actions !== undefined && parsedData.actions !== null) {
                BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
            }
            if (!addToScene) {
                container.removeAllFromScene();
            }
        }
        catch (err) {
            var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
            if (onError) {
                onError(msg, err);
            }
            else {
                BABYLON.Tools.Log(msg);
                throw err;
            }
        }
        finally {
            if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
                BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
            }
        }
        return container;
    };
    BABYLON.SceneLoader.RegisterPlugin({
        name: "babylon.js",
        extensions: ".babylon",
        canDirectLoad: function (data) {
            if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
                return true;
            }
            return false;
        },
        importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
            // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
            // when SceneLoader.debugLogging = true (default), or exception encountered.
            // Everything stored in var log instead of writing separate lines to support only writing in exception,
            // and avoid problems with multiple concurrent .babylon loads.
            var log = "importMesh has failed JSON parse";
            try {
                var parsedData = JSON.parse(data);
                log = "";
                var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
                if (!meshesNames) {
                    meshesNames = null;
                }
                else if (!Array.isArray(meshesNames)) {
                    meshesNames = [meshesNames];
                }
                var hierarchyIds = new Array();
                if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
                    var loadedSkeletonsIds = [];
                    var loadedMaterialsIds = [];
                    var index;
                    var cache;
                    for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
                        var parsedMesh = parsedData.meshes[index];
                        if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
                            if (meshesNames !== null) {
                                // Remove found mesh name from list.
                                delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
                            }
                            //Geometry?
                            if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
                                //does the file contain geometries?
                                if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
                                    //find the correct geometry and add it to the scene
                                    var found = false;
                                    ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
                                        if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
                                            return;
                                        }
                                        else {
                                            parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
                                                if (parsedGeometryData.id === parsedMesh.geometryId) {
                                                    switch (geometryType) {
                                                        case "boxes":
                                                            BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "spheres":
                                                            BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "cylinders":
                                                            BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "toruses":
                                                            BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "grounds":
                                                            BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "planes":
                                                            BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "torusKnots":
                                                            BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
                                                            break;
                                                        case "vertexData":
                                                            BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
                                                            break;
                                                    }
                                                    found = true;
                                                }
                                            });
                                        }
                                    });
                                    if (found === false) {
                                        BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
                                    }
                                }
                            }
                            // Material ?
                            if (parsedMesh.materialId) {
                                var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
                                if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
                                    for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
                                        var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
                                        if (parsedMultiMaterial.id === parsedMesh.materialId) {
                                            for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
                                                var subMatId = parsedMultiMaterial.materials[matIndex];
                                                loadedMaterialsIds.push(subMatId);
                                                var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
                                                if (mat) {
                                                    log += "\n\tMaterial " + mat.toString(fullDetails);
                                                }
                                            }
                                            loadedMaterialsIds.push(parsedMultiMaterial.id);
                                            var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
                                            if (mmat) {
                                                materialFound = true;
                                                log += "\n\tMulti-Material " + mmat.toString(fullDetails);
                                            }
                                            break;
                                        }
                                    }
                                }
                                if (materialFound === false) {
                                    loadedMaterialsIds.push(parsedMesh.materialId);
                                    var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
                                    if (!mat) {
                                        BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
                                    }
                                    else {
                                        log += "\n\tMaterial " + mat.toString(fullDetails);
                                    }
                                }
                            }
                            // Skeleton ?
                            if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
                                var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
                                if (skeletonAlreadyLoaded === false) {
                                    for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
                                        var parsedSkeleton = parsedData.skeletons[skeletonIndex];
                                        if (parsedSkeleton.id === parsedMesh.skeletonId) {
                                            var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
                                            skeletons.push(skeleton);
                                            loadedSkeletonsIds.push(parsedSkeleton.id);
                                            log += "\n\tSkeleton " + skeleton.toString(fullDetails);
                                        }
                                    }
                                }
                            }
                            // Morph targets ?
                            if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
                                for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
                                    var managerData = _a[_i];
                                    BABYLON.MorphTargetManager.Parse(managerData, scene);
                                }
                            }
                            var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
                            meshes.push(mesh);
                            log += "\n\tMesh " + mesh.toString(fullDetails);
                        }
                    }
                    // Connecting parents
                    var currentMesh;
                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                        currentMesh = scene.meshes[index];
                        if (currentMesh._waitingParentId) {
                            currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
                            currentMesh._waitingParentId = null;
                        }
                    }
                    // freeze and compute world matrix application
                    for (index = 0, cache = scene.meshes.length; index < cache; index++) {
                        currentMesh = scene.meshes[index];
                        if (currentMesh._waitingFreezeWorldMatrix) {
                            currentMesh.freezeWorldMatrix();
                            currentMesh._waitingFreezeWorldMatrix = null;
                        }
                        else {
                            currentMesh.computeWorldMatrix(true);
                        }
                    }
                }
                // Particles
                if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
                    var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
                    if (parser) {
                        for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
                            var parsedParticleSystem = parsedData.particleSystems[index];
                            if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
                                particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
                            }
                        }
                    }
                }
                return true;
            }
            catch (err) {
                var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
                if (onError) {
                    onError(msg, err);
                }
                else {
                    BABYLON.Tools.Log(msg);
                    throw err;
                }
            }
            finally {
                if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
                    BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
                }
            }
            return false;
        },
        load: function (scene, data, rootUrl, onError) {
            // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
            // when SceneLoader.debugLogging = true (default), or exception encountered.
            // Everything stored in var log instead of writing separate lines to support only writing in exception,
            // and avoid problems with multiple concurrent .babylon loads.
            var log = "importScene has failed JSON parse";
            try {
                var parsedData = JSON.parse(data);
                log = "";
                // Scene
                if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
                    scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
                }
                if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
                    scene.autoClear = parsedData.autoClear;
                }
                if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
                    scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
                }
                if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
                    scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
                }
                if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
                    scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
                }
                // Fog
                if (parsedData.fogMode && parsedData.fogMode !== 0) {
                    scene.fogMode = parsedData.fogMode;
                    scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
                    scene.fogStart = parsedData.fogStart;
                    scene.fogEnd = parsedData.fogEnd;
                    scene.fogDensity = parsedData.fogDensity;
                    log += "\tFog mode for scene:  ";
                    switch (scene.fogMode) {
                        // getters not compiling, so using hardcoded
                        case 1:
                            log += "exp\n";
                            break;
                        case 2:
                            log += "exp2\n";
                            break;
                        case 3:
                            log += "linear\n";
                            break;
                    }
                }
                //Physics
                if (parsedData.physicsEnabled) {
                    var physicsPlugin;
                    if (parsedData.physicsEngine === "cannon") {
                        physicsPlugin = new BABYLON.CannonJSPlugin();
                    }
                    else if (parsedData.physicsEngine === "oimo") {
                        physicsPlugin = new BABYLON.OimoJSPlugin();
                    }
                    log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
                    //else - default engine, which is currently oimo
                    var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
                    scene.enablePhysics(physicsGravity, physicsPlugin);
                }
                // Metadata
                if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
                    scene.metadata = parsedData.metadata;
                }
                //collisions, if defined. otherwise, default is true
                if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
                    scene.collisionsEnabled = parsedData.collisionsEnabled;
                }
                scene.workerCollisions = !!parsedData.workerCollisions;
                var container = loadAssetContainer(scene, data, rootUrl, onError, true);
                if (!container) {
                    return false;
                }
                if (parsedData.autoAnimate) {
                    scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
                }
                if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
                    scene.setActiveCameraByID(parsedData.activeCameraID);
                }
                // Environment texture
                if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
                    if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
                        var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
                        var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
                        if (parsedData.environmentTextureRotationY) {
                            hdrTexture.rotationY = parsedData.environmentTextureRotationY;
                        }
                        scene.environmentTexture = hdrTexture;
                    }
                    else {
                        var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
                        if (parsedData.environmentTextureRotationY) {
                            cubeTexture.rotationY = parsedData.environmentTextureRotationY;
                        }
                        scene.environmentTexture = cubeTexture;
                    }
                    if (parsedData.createDefaultSkybox === true) {
                        var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
                        var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
                        scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
                    }
                }
                // Finish
                return true;
            }
            catch (err) {
                var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
                if (onError) {
                    onError(msg, err);
                }
                else {
                    BABYLON.Tools.Log(msg);
                    throw err;
                }
            }
            finally {
                if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
                    BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
                }
            }
            return false;
        },
        loadAssetContainer: function (scene, data, rootUrl, onError) {
            var container = loadAssetContainer(scene, data, rootUrl, onError);
            return container;
        }
    });
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.babylonFileLoader.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to help managing file picking and drag'n'drop
     */
    var FilesInput = /** @class */ (function () {
        /**
         * Creates a new FilesInput
         * @param engine defines the rendering engine
         * @param scene defines the hosting scene
         * @param sceneLoadedCallback callback called when scene is loaded
         * @param progressCallback callback called to track progress
         * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
         * @param textureLoadingCallback callback called when a texture is loading
         * @param startingProcessingFilesCallback callback called when the system is about to process all files
         * @param onReloadCallback callback called when a reload is requested
         * @param errorCallback callback call if an error occurs
         */
        function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
            /**
             * Callback called when a file is processed
             */
            this.onProcessFileCallback = function () { return true; };
            this._engine = engine;
            this._currentScene = scene;
            this._sceneLoadedCallback = sceneLoadedCallback;
            this._progressCallback = progressCallback;
            this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
            this._textureLoadingCallback = textureLoadingCallback;
            this._startingProcessingFilesCallback = startingProcessingFilesCallback;
            this._onReloadCallback = onReloadCallback;
            this._errorCallback = errorCallback;
        }
        /**
         * Calls this function to listen to drag'n'drop events on a specific DOM element
         * @param elementToMonitor defines the DOM element to track
         */
        FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
            var _this = this;
            if (elementToMonitor) {
                this._elementToMonitor = elementToMonitor;
                this._dragEnterHandler = function (e) { _this.drag(e); };
                this._dragOverHandler = function (e) { _this.drag(e); };
                this._dropHandler = function (e) { _this.drop(e); };
                this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
                this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
                this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
            }
        };
        /**
         * Release all associated resources
         */
        FilesInput.prototype.dispose = function () {
            if (!this._elementToMonitor) {
                return;
            }
            this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
            this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
            this._elementToMonitor.removeEventListener("drop", this._dropHandler);
        };
        FilesInput.prototype.renderFunction = function () {
            if (this._additionalRenderLoopLogicCallback) {
                this._additionalRenderLoopLogicCallback();
            }
            if (this._currentScene) {
                if (this._textureLoadingCallback) {
                    var remaining = this._currentScene.getWaitingItemsCount();
                    if (remaining > 0) {
                        this._textureLoadingCallback(remaining);
                    }
                }
                this._currentScene.render();
            }
        };
        FilesInput.prototype.drag = function (e) {
            e.stopPropagation();
            e.preventDefault();
        };
        FilesInput.prototype.drop = function (eventDrop) {
            eventDrop.stopPropagation();
            eventDrop.preventDefault();
            this.loadFiles(eventDrop);
        };
        FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
            var _this = this;
            var reader = folder.createReader();
            var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
            reader.readEntries(function (entries) {
                remaining.count += entries.length;
                for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
                    var entry = entries_1[_i];
                    if (entry.isFile) {
                        entry.file(function (file) {
                            file.correctName = relativePath + file.name;
                            files.push(file);
                            if (--remaining.count === 0) {
                                callback();
                            }
                        });
                    }
                    else if (entry.isDirectory) {
                        _this._traverseFolder(entry, files, remaining, callback);
                    }
                }
                if (--remaining.count) {
                    callback();
                }
            });
        };
        FilesInput.prototype._processFiles = function (files) {
            for (var i = 0; i < files.length; i++) {
                var name = files[i].correctName.toLowerCase();
                var extension = name.split('.').pop();
                if (!this.onProcessFileCallback(files[i], name, extension)) {
                    continue;
                }
                if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
                    && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
                    this._sceneFileToLoad = files[i];
                }
                FilesInput.FilesToLoad[name] = files[i];
            }
        };
        /**
         * Load files from a drop event
         * @param event defines the drop event to use as source
         */
        FilesInput.prototype.loadFiles = function (event) {
            var _this = this;
            // Handling data transfer via drag'n'drop
            if (event && event.dataTransfer && event.dataTransfer.files) {
                this._filesToLoad = event.dataTransfer.files;
            }
            // Handling files from input files
            if (event && event.target && event.target.files) {
                this._filesToLoad = event.target.files;
            }
            if (!this._filesToLoad || this._filesToLoad.length === 0) {
                return;
            }
            if (this._startingProcessingFilesCallback) {
                this._startingProcessingFilesCallback(this._filesToLoad);
            }
            if (this._filesToLoad && this._filesToLoad.length > 0) {
                var files_1 = new Array();
                var folders = [];
                var items = event.dataTransfer ? event.dataTransfer.items : null;
                for (var i = 0; i < this._filesToLoad.length; i++) {
                    var fileToLoad = this._filesToLoad[i];
                    var name_1 = fileToLoad.name.toLowerCase();
                    var entry = void 0;
                    fileToLoad.correctName = name_1;
                    if (items) {
                        var item = items[i];
                        if (item.getAsEntry) {
                            entry = item.getAsEntry();
                        }
                        else if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                        }
                    }
                    if (!entry) {
                        files_1.push(fileToLoad);
                    }
                    else {
                        if (entry.isDirectory) {
                            folders.push(entry);
                        }
                        else {
                            files_1.push(fileToLoad);
                        }
                    }
                }
                if (folders.length === 0) {
                    this._processFiles(files_1);
                    this._processReload();
                }
                else {
                    var remaining = { count: folders.length };
                    for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
                        var folder = folders_1[_i];
                        this._traverseFolder(folder, files_1, remaining, function () {
                            _this._processFiles(files_1);
                            if (remaining.count === 0) {
                                _this._processReload();
                            }
                        });
                    }
                }
            }
        };
        FilesInput.prototype._processReload = function () {
            if (this._onReloadCallback) {
                this._onReloadCallback(this._sceneFileToLoad);
            }
            else {
                this.reload();
            }
        };
        /**
         * Reload the current scene from the loaded files
         */
        FilesInput.prototype.reload = function () {
            var _this = this;
            // If a scene file has been provided
            if (this._sceneFileToLoad) {
                if (this._currentScene) {
                    if (BABYLON.Tools.errorsCount > 0) {
                        BABYLON.Tools.ClearLogCache();
                    }
                    this._engine.stopRenderLoop();
                }
                BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
                    if (_this._progressCallback) {
                        _this._progressCallback(progress);
                    }
                }).then(function (scene) {
                    if (_this._currentScene) {
                        _this._currentScene.dispose();
                    }
                    _this._currentScene = scene;
                    if (_this._sceneLoadedCallback) {
                        _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
                    }
                    // Wait for textures and shaders to be ready
                    _this._currentScene.executeWhenReady(function () {
                        _this._engine.runRenderLoop(function () {
                            _this.renderFunction();
                        });
                    });
                }).catch(function (error) {
                    if (_this._errorCallback) {
                        _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
                    }
                });
            }
            else {
                BABYLON.Tools.Error("Please provide a valid .babylon file.");
            }
        };
        /**
         * List of files ready to be loaded
         */
        FilesInput.FilesToLoad = {};
        return FilesInput;
    }());
    BABYLON.FilesInput = FilesInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.filesInput.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store custom tags
     */
    var Tags = /** @class */ (function () {
        function Tags() {
        }
        /**
         * Adds support for tags on the given object
         * @param obj defines the object to use
         */
        Tags.EnableFor = function (obj) {
            obj._tags = obj._tags || {};
            obj.hasTags = function () {
                return Tags.HasTags(obj);
            };
            obj.addTags = function (tagsString) {
                return Tags.AddTagsTo(obj, tagsString);
            };
            obj.removeTags = function (tagsString) {
                return Tags.RemoveTagsFrom(obj, tagsString);
            };
            obj.matchesTagsQuery = function (tagsQuery) {
                return Tags.MatchesQuery(obj, tagsQuery);
            };
        };
        /**
         * Removes tags support
         * @param obj defines the object to use
         */
        Tags.DisableFor = function (obj) {
            delete obj._tags;
            delete obj.hasTags;
            delete obj.addTags;
            delete obj.removeTags;
            delete obj.matchesTagsQuery;
        };
        /**
         * Gets a boolean indicating if the given object has tags
         * @param obj defines the object to use
         * @returns a boolean
         */
        Tags.HasTags = function (obj) {
            if (!obj._tags) {
                return false;
            }
            return !BABYLON.Tools.IsEmpty(obj._tags);
        };
        /**
         * Gets the tags available on a given object
         * @param obj defines the object to use
         * @param asString defines if the tags must be returned as a string instead of an array of strings
         * @returns the tags
         */
        Tags.GetTags = function (obj, asString) {
            if (asString === void 0) { asString = true; }
            if (!obj._tags) {
                return null;
            }
            if (asString) {
                var tagsArray = [];
                for (var tag in obj._tags) {
                    if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
                        tagsArray.push(tag);
                    }
                }
                return tagsArray.join(" ");
            }
            else {
                return obj._tags;
            }
        };
        /**
         * Adds tags to an object
         * @param obj defines the object to use
         * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
         * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
         */
        Tags.AddTagsTo = function (obj, tagsString) {
            if (!tagsString) {
                return;
            }
            if (typeof tagsString !== "string") {
                return;
            }
            var tags = tagsString.split(" ");
            tags.forEach(function (tag, index, array) {
                Tags._AddTagTo(obj, tag);
            });
        };
        /**
         * @hidden
         */
        Tags._AddTagTo = function (obj, tag) {
            tag = tag.trim();
            if (tag === "" || tag === "true" || tag === "false") {
                return;
            }
            if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
                return;
            }
            Tags.EnableFor(obj);
            obj._tags[tag] = true;
        };
        /**
         * Removes specific tags from a specific object
         * @param obj defines the object to use
         * @param tagsString defines the tags to remove
         */
        Tags.RemoveTagsFrom = function (obj, tagsString) {
            if (!Tags.HasTags(obj)) {
                return;
            }
            var tags = tagsString.split(" ");
            for (var t in tags) {
                Tags._RemoveTagFrom(obj, tags[t]);
            }
        };
        /**
         * @hidden
         */
        Tags._RemoveTagFrom = function (obj, tag) {
            delete obj._tags[tag];
        };
        /**
         * Defines if tags hosted on an object match a given query
         * @param obj defines the object to use
         * @param tagsQuery defines the tag query
         * @returns a boolean
         */
        Tags.MatchesQuery = function (obj, tagsQuery) {
            if (tagsQuery === undefined) {
                return true;
            }
            if (tagsQuery === "") {
                return Tags.HasTags(obj);
            }
            return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
        };
        return Tags;
    }());
    BABYLON.Tags = Tags;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.tags.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to evalaute queries containing `and` and `or` operators
     */
    var AndOrNotEvaluator = /** @class */ (function () {
        function AndOrNotEvaluator() {
        }
        /**
         * Evaluate a query
         * @param query defines the query to evaluate
         * @param evaluateCallback defines the callback used to filter result
         * @returns true if the query matches
         */
        AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
            if (!query.match(/\([^\(\)]*\)/g)) {
                query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
            }
            else {
                query = query.replace(/\([^\(\)]*\)/g, function (r) {
                    // remove parenthesis
                    r = r.slice(1, r.length - 1);
                    return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
                });
            }
            if (query === "true") {
                return true;
            }
            if (query === "false") {
                return false;
            }
            return AndOrNotEvaluator.Eval(query, evaluateCallback);
        };
        AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
            evaluateCallback = evaluateCallback || (function (r) {
                return r === "true" ? true : false;
            });
            var result;
            var or = parenthesisContent.split("||");
            for (var i in or) {
                if (or.hasOwnProperty(i)) {
                    var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
                    var and = ori.split("&&");
                    if (and.length > 1) {
                        for (var j = 0; j < and.length; ++j) {
                            var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
                            if (andj !== "true" && andj !== "false") {
                                if (andj[0] === "!") {
                                    result = !evaluateCallback(andj.substring(1));
                                }
                                else {
                                    result = evaluateCallback(andj);
                                }
                            }
                            else {
                                result = andj === "true" ? true : false;
                            }
                            if (!result) { // no need to continue since 'false && ... && ...' will always return false
                                ori = "false";
                                break;
                            }
                        }
                    }
                    if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
                        result = true;
                        break;
                    }
                    // result equals false (or undefined)
                    if (ori !== "true" && ori !== "false") {
                        if (ori[0] === "!") {
                            result = !evaluateCallback(ori.substring(1));
                        }
                        else {
                            result = evaluateCallback(ori);
                        }
                    }
                    else {
                        result = ori === "true" ? true : false;
                    }
                }
            }
            // the whole parenthesis scope is replaced by 'true' or 'false'
            return result ? "true" : "false";
        };
        AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
            booleanString = booleanString.replace(/^[\s!]+/, function (r) {
                // remove whitespaces
                r = r.replace(/[\s]/g, function () { return ""; });
                return r.length % 2 ? "!" : "";
            });
            booleanString = booleanString.trim();
            if (booleanString === "!true") {
                booleanString = "false";
            }
            else if (booleanString === "!false") {
                booleanString = "true";
            }
            return booleanString;
        };
        return AndOrNotEvaluator;
    }());
    BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.andOrNotEvaluator.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to enable access to IndexedDB
     * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
     */
    var Database = /** @class */ (function () {
        /**
         * Creates a new Database
         * @param urlToScene defines the url to load the scene
         * @param callbackManifestChecked defines the callback to use when manifest is checked
         * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
         */
        function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
            if (disableManifestCheck === void 0) { disableManifestCheck = false; }
            var _this = this;
            // Handling various flavors of prefixed version of IndexedDB
            this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
            this.callbackManifestChecked = callbackManifestChecked;
            this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
            this.db = null;
            this._enableSceneOffline = false;
            this._enableTexturesOffline = false;
            this.manifestVersionFound = 0;
            this.mustUpdateRessources = false;
            this.hasReachedQuota = false;
            if (!Database.IDBStorageEnabled) {
                this.callbackManifestChecked(true);
            }
            else {
                if (disableManifestCheck) {
                    this._enableSceneOffline = true;
                    this._enableTexturesOffline = true;
                    this.manifestVersionFound = 1;
                    BABYLON.Tools.SetImmediate(function () {
                        _this.callbackManifestChecked(true);
                    });
                }
                else {
                    this._checkManifestFile();
                }
            }
        }
        Object.defineProperty(Database.prototype, "enableSceneOffline", {
            /**
             * Gets a boolean indicating if scene must be saved in the database
             */
            get: function () {
                return this._enableSceneOffline;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Database.prototype, "enableTexturesOffline", {
            /**
             * Gets a boolean indicating if textures must be saved in the database
             */
            get: function () {
                return this._enableTexturesOffline;
            },
            enumerable: true,
            configurable: true
        });
        Database.prototype._checkManifestFile = function () {
            var _this = this;
            var noManifestFile = function () {
                _this._enableSceneOffline = false;
                _this._enableTexturesOffline = false;
                _this.callbackManifestChecked(false);
            };
            var timeStampUsed = false;
            var manifestURL = this.currentSceneUrl + ".manifest";
            var xhr = new XMLHttpRequest();
            if (navigator.onLine) {
                // Adding a timestamp to by-pass browsers' cache
                timeStampUsed = true;
                manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
            }
            xhr.open("GET", manifestURL, true);
            xhr.addEventListener("load", function () {
                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
                    try {
                        var manifestFile = JSON.parse(xhr.response);
                        _this._enableSceneOffline = manifestFile.enableSceneOffline;
                        _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
                        if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
                            _this.manifestVersionFound = manifestFile.version;
                        }
                        if (_this.callbackManifestChecked) {
                            _this.callbackManifestChecked(true);
                        }
                    }
                    catch (ex) {
                        noManifestFile();
                    }
                }
                else {
                    noManifestFile();
                }
            }, false);
            xhr.addEventListener("error", function (event) {
                if (timeStampUsed) {
                    timeStampUsed = false;
                    // Let's retry without the timeStamp
                    // It could fail when coupled with HTML5 Offline API
                    var retryManifestURL = _this.currentSceneUrl + ".manifest";
                    xhr.open("GET", retryManifestURL, true);
                    xhr.send();
                }
                else {
                    noManifestFile();
                }
            }, false);
            try {
                xhr.send();
            }
            catch (ex) {
                BABYLON.Tools.Error("Error on XHR send request.");
                this.callbackManifestChecked(false);
            }
        };
        /**
         * Open the database and make it available
         * @param successCallback defines the callback to call on success
         * @param errorCallback defines the callback to call on error
         */
        Database.prototype.openAsync = function (successCallback, errorCallback) {
            var _this = this;
            var handleError = function () {
                _this.isSupported = false;
                if (errorCallback) {
                    errorCallback();
                }
            };
            if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
                // Your browser doesn't support IndexedDB
                this.isSupported = false;
                if (errorCallback) {
                    errorCallback();
                }
            }
            else {
                // If the DB hasn't been opened or created yet
                if (!this.db) {
                    this.hasReachedQuota = false;
                    this.isSupported = true;
                    var request = this.idbFactory.open("babylonjs", 1);
                    // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
                    request.onerror = function (event) {
                        handleError();
                    };
                    // executes when a version change transaction cannot complete due to other active transactions
                    request.onblocked = function (event) {
                        BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
                        handleError();
                    };
                    // DB has been opened successfully
                    request.onsuccess = function (event) {
                        _this.db = request.result;
                        successCallback();
                    };
                    // Initialization of the DB. Creating Scenes & Textures stores
                    request.onupgradeneeded = function (event) {
                        _this.db = (event.target).result;
                        if (_this.db) {
                            try {
                                _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
                                _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
                                _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
                            }
                            catch (ex) {
                                BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
                                handleError();
                            }
                        }
                    };
                }
                // DB has already been created and opened
                else {
                    if (successCallback) {
                        successCallback();
                    }
                }
            }
        };
        /**
         * Loads an image from the database
         * @param url defines the url to load from
         * @param image defines the target DOM image
         */
        Database.prototype.loadImageFromDB = function (url, image) {
            var _this = this;
            var completeURL = Database._ReturnFullUrlLocation(url);
            var saveAndLoadImage = function () {
                if (!_this.hasReachedQuota && _this.db !== null) {
                    // the texture is not yet in the DB, let's try to save it
                    _this._saveImageIntoDBAsync(completeURL, image);
                }
                // If the texture is not in the DB and we've reached the DB quota limit
                // let's load it directly from the web
                else {
                    image.src = url;
                }
            };
            if (!this.mustUpdateRessources) {
                this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
            }
            // First time we're download the images or update requested in the manifest file by a version change
            else {
                saveAndLoadImage();
            }
        };
        Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
            if (this.isSupported && this.db !== null) {
                var texture;
                var transaction = this.db.transaction(["textures"]);
                transaction.onabort = function (event) {
                    image.src = url;
                };
                transaction.oncomplete = function (event) {
                    var blobTextureURL;
                    if (texture) {
                        var URL = window.URL || window.webkitURL;
                        blobTextureURL = URL.createObjectURL(texture.data);
                        image.onerror = function () {
                            BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
                            image.src = url;
                        };
                        image.src = blobTextureURL;
                    }
                    else {
                        notInDBCallback();
                    }
                };
                var getRequest = transaction.objectStore("textures").get(url);
                getRequest.onsuccess = function (event) {
                    texture = (event.target).result;
                };
                getRequest.onerror = function (event) {
                    BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
                    image.src = url;
                };
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                image.src = url;
            }
        };
        Database.prototype._saveImageIntoDBAsync = function (url, image) {
            var _this = this;
            if (this.isSupported) {
                // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
                var generateBlobUrl = function () {
                    var blobTextureURL;
                    if (blob) {
                        var URL = window.URL || window.webkitURL;
                        try {
                            blobTextureURL = URL.createObjectURL(blob);
                        }
                        // Chrome is raising a type error if we're setting the oneTimeOnly parameter
                        catch (ex) {
                            blobTextureURL = URL.createObjectURL(blob);
                        }
                    }
                    if (blobTextureURL) {
                        image.src = blobTextureURL;
                    }
                };
                if (Database.IsUASupportingBlobStorage) { // Create XHR
                    var xhr = new XMLHttpRequest(), blob;
                    xhr.open("GET", url, true);
                    xhr.responseType = "blob";
                    xhr.addEventListener("load", function () {
                        if (xhr.status === 200 && _this.db) {
                            // Blob as response (XHR2)
                            blob = xhr.response;
                            var transaction = _this.db.transaction(["textures"], "readwrite");
                            // the transaction could abort because of a QuotaExceededError error
                            transaction.onabort = function (event) {
                                try {
                                    //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
                                    var srcElement = (event.srcElement || event.target);
                                    var error = srcElement.error;
                                    if (error && error.name === "QuotaExceededError") {
                                        _this.hasReachedQuota = true;
                                    }
                                }
                                catch (ex) { }
                                generateBlobUrl();
                            };
                            transaction.oncomplete = function (event) {
                                generateBlobUrl();
                            };
                            var newTexture = { textureUrl: url, data: blob };
                            try {
                                // Put the blob into the dabase
                                var addRequest = transaction.objectStore("textures").put(newTexture);
                                addRequest.onsuccess = function (event) {
                                };
                                addRequest.onerror = function (event) {
                                    generateBlobUrl();
                                };
                            }
                            catch (ex) {
                                // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
                                if (ex.code === 25) {
                                    Database.IsUASupportingBlobStorage = false;
                                }
                                image.src = url;
                            }
                        }
                        else {
                            image.src = url;
                        }
                    }, false);
                    xhr.addEventListener("error", function (event) {
                        BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
                        image.src = url;
                    }, false);
                    xhr.send();
                }
                else {
                    image.src = url;
                }
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                image.src = url;
            }
        };
        Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
            var _this = this;
            var updateVersion = function () {
                // the version is not yet in the DB or we need to update it
                _this._saveVersionIntoDBAsync(url, versionLoaded);
            };
            this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
        };
        Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
            var _this = this;
            if (this.isSupported && this.db) {
                var version;
                try {
                    var transaction = this.db.transaction(["versions"]);
                    transaction.oncomplete = function (event) {
                        if (version) {
                            // If the version in the JSON file is different from the version in DB
                            if (_this.manifestVersionFound !== version.data) {
                                _this.mustUpdateRessources = true;
                                updateInDBCallback();
                            }
                            else {
                                callback(version.data);
                            }
                        }
                        // version was not found in DB
                        else {
                            _this.mustUpdateRessources = true;
                            updateInDBCallback();
                        }
                    };
                    transaction.onabort = function (event) {
                        callback(-1);
                    };
                    var getRequest = transaction.objectStore("versions").get(url);
                    getRequest.onsuccess = function (event) {
                        version = (event.target).result;
                    };
                    getRequest.onerror = function (event) {
                        BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
                        callback(-1);
                    };
                }
                catch (ex) {
                    BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
                    callback(-1);
                }
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                callback(-1);
            }
        };
        Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
            var _this = this;
            if (this.isSupported && !this.hasReachedQuota && this.db) {
                try {
                    // Open a transaction to the database
                    var transaction = this.db.transaction(["versions"], "readwrite");
                    // the transaction could abort because of a QuotaExceededError error
                    transaction.onabort = function (event) {
                        try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
                            var error = event.srcElement['error'];
                            if (error && error.name === "QuotaExceededError") {
                                _this.hasReachedQuota = true;
                            }
                        }
                        catch (ex) { }
                        callback(-1);
                    };
                    transaction.oncomplete = function (event) {
                        callback(_this.manifestVersionFound);
                    };
                    var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
                    // Put the scene into the database
                    var addRequest = transaction.objectStore("versions").put(newVersion);
                    addRequest.onsuccess = function (event) {
                    };
                    addRequest.onerror = function (event) {
                        BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
                    };
                }
                catch (ex) {
                    BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
                    callback(-1);
                }
            }
            else {
                callback(-1);
            }
        };
        /**
         * Loads a file from database
         * @param url defines the URL to load from
         * @param sceneLoaded defines a callback to call on success
         * @param progressCallBack defines a callback to call when progress changed
         * @param errorCallback defines a callback to call on error
         * @param useArrayBuffer defines a boolean to use array buffer instead of text string
         */
        Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
            var _this = this;
            var completeUrl = Database._ReturnFullUrlLocation(url);
            var saveAndLoadFile = function () {
                // the scene is not yet in the DB, let's try to save it
                _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
            };
            this._checkVersionFromDB(completeUrl, function (version) {
                if (version !== -1) {
                    if (!_this.mustUpdateRessources) {
                        _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
                    }
                    else {
                        _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
                    }
                }
                else {
                    if (errorCallback) {
                        errorCallback();
                    }
                }
            });
        };
        Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
            if (this.isSupported && this.db) {
                var targetStore;
                if (url.indexOf(".babylon") !== -1) {
                    targetStore = "scenes";
                }
                else {
                    targetStore = "textures";
                }
                var file;
                var transaction = this.db.transaction([targetStore]);
                transaction.oncomplete = function (event) {
                    if (file) {
                        callback(file.data);
                    }
                    // file was not found in DB
                    else {
                        notInDBCallback();
                    }
                };
                transaction.onabort = function (event) {
                    notInDBCallback();
                };
                var getRequest = transaction.objectStore(targetStore).get(url);
                getRequest.onsuccess = function (event) {
                    file = (event.target).result;
                };
                getRequest.onerror = function (event) {
                    BABYLON.Tools.Error("Error loading file " + url + " from DB.");
                    notInDBCallback();
                };
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                callback();
            }
        };
        Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
            var _this = this;
            if (this.isSupported) {
                var targetStore;
                if (url.indexOf(".babylon") !== -1) {
                    targetStore = "scenes";
                }
                else {
                    targetStore = "textures";
                }
                // Create XHR
                var xhr = new XMLHttpRequest();
                var fileData;
                xhr.open("GET", url + "?" + Date.now(), true);
                if (useArrayBuffer) {
                    xhr.responseType = "arraybuffer";
                }
                if (progressCallback) {
                    xhr.onprogress = progressCallback;
                }
                xhr.addEventListener("load", function () {
                    if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
                        // Blob as response (XHR2)
                        //fileData = xhr.responseText;
                        fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
                        if (!_this.hasReachedQuota && _this.db) {
                            // Open a transaction to the database
                            var transaction = _this.db.transaction([targetStore], "readwrite");
                            // the transaction could abort because of a QuotaExceededError error
                            transaction.onabort = function (event) {
                                try {
                                    //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
                                    var error = event.srcElement['error'];
                                    if (error && error.name === "QuotaExceededError") {
                                        _this.hasReachedQuota = true;
                                    }
                                }
                                catch (ex) { }
                                callback(fileData);
                            };
                            transaction.oncomplete = function (event) {
                                callback(fileData);
                            };
                            var newFile;
                            if (targetStore === "scenes") {
                                newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
                            }
                            else {
                                newFile = { textureUrl: url, data: fileData };
                            }
                            try {
                                // Put the scene into the database
                                var addRequest = transaction.objectStore(targetStore).put(newFile);
                                addRequest.onsuccess = function (event) {
                                };
                                addRequest.onerror = function (event) {
                                    BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
                                };
                            }
                            catch (ex) {
                                callback(fileData);
                            }
                        }
                        else {
                            callback(fileData);
                        }
                    }
                    else {
                        if (xhr.status >= 400 && errorCallback) {
                            errorCallback(xhr);
                        }
                        else {
                            callback();
                        }
                    }
                }, false);
                xhr.addEventListener("error", function (event) {
                    BABYLON.Tools.Error("error on XHR request.");
                    callback();
                }, false);
                xhr.send();
            }
            else {
                BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
                callback();
            }
        };
        /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
        Database.IsUASupportingBlobStorage = true;
        /** Gets a boolean indicating if Database storate is enabled */
        Database.IDBStorageEnabled = true;
        Database._ParseURL = function (url) {
            var a = document.createElement('a');
            a.href = url;
            var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
            var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
            var absLocation = url.substring(0, url.indexOf(fileName, 0));
            return absLocation;
        };
        Database._ReturnFullUrlLocation = function (url) {
            if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
                return (Database._ParseURL(window.location.href) + url);
            }
            else {
                return url;
            }
        };
        return Database;
    }());
    BABYLON.Database = Database;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.database.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents all the required information to add a fresnel effect on a material:
     * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
     */
    var FresnelParameters = /** @class */ (function () {
        function FresnelParameters() {
            this._isEnabled = true;
            /**
             * Define the color used on edges (grazing angle)
             */
            this.leftColor = BABYLON.Color3.White();
            /**
             * Define the color used on center
             */
            this.rightColor = BABYLON.Color3.Black();
            /**
             * Define bias applied to computed fresnel term
             */
            this.bias = 0;
            /**
             * Defined the power exponent applied to fresnel term
             */
            this.power = 1;
        }
        Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
            /**
             * Define if the fresnel effect is enable or not.
             */
            get: function () {
                return this._isEnabled;
            },
            set: function (value) {
                if (this._isEnabled === value) {
                    return;
                }
                this._isEnabled = value;
                BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Clones the current fresnel and its valuues
         * @returns a clone fresnel configuration
         */
        FresnelParameters.prototype.clone = function () {
            var newFresnelParameters = new FresnelParameters();
            BABYLON.Tools.DeepCopy(this, newFresnelParameters);
            return newFresnelParameters;
        };
        /**
         * Serializes the current fresnel parameters to a JSON representation.
         * @return the JSON serialization
         */
        FresnelParameters.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.isEnabled = this.isEnabled;
            serializationObject.leftColor = this.leftColor.asArray();
            serializationObject.rightColor = this.rightColor.asArray();
            serializationObject.bias = this.bias;
            serializationObject.power = this.power;
            return serializationObject;
        };
        /**
         * Parse a JSON object and deserialize it to a new Fresnel parameter object.
         * @param parsedFresnelParameters Define the JSON representation
         * @returns the parsed parameters
         */
        FresnelParameters.Parse = function (parsedFresnelParameters) {
            var fresnelParameters = new FresnelParameters();
            fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
            fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
            fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
            fresnelParameters.bias = parsedFresnelParameters.bias;
            fresnelParameters.power = parsedFresnelParameters.power || 1.0;
            return fresnelParameters;
        };
        return FresnelParameters;
    }());
    BABYLON.FresnelParameters = FresnelParameters;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.fresnelParameters.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * A multi-material is used to apply different materials to different parts of the same object without the need of
     * separate meshes. This can be use to improve performances.
     * @see http://doc.babylonjs.com/how_to/multi_materials
     */
    var MultiMaterial = /** @class */ (function (_super) {
        __extends(MultiMaterial, _super);
        /**
         * Instantiates a new Multi Material
         * A multi-material is used to apply different materials to different parts of the same object without the need of
         * separate meshes. This can be use to improve performances.
         * @see http://doc.babylonjs.com/how_to/multi_materials
         * @param name Define the name in the scene
         * @param scene Define the scene the material belongs to
         */
        function MultiMaterial(name, scene) {
            var _this = _super.call(this, name, scene, true) || this;
            scene.multiMaterials.push(_this);
            _this.subMaterials = new Array();
            _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
            return _this;
        }
        Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
            /**
             * Gets or Sets the list of Materials used within the multi material.
             * They need to be ordered according to the submeshes order in the associated mesh
             */
            get: function () {
                return this._subMaterials;
            },
            set: function (value) {
                this._subMaterials = value;
                this._hookArray(value);
            },
            enumerable: true,
            configurable: true
        });
        MultiMaterial.prototype._hookArray = function (array) {
            var _this = this;
            var oldPush = array.push;
            array.push = function () {
                var items = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    items[_i] = arguments[_i];
                }
                var result = oldPush.apply(array, items);
                _this._markAllSubMeshesAsTexturesDirty();
                return result;
            };
            var oldSplice = array.splice;
            array.splice = function (index, deleteCount) {
                var deleted = oldSplice.apply(array, [index, deleteCount]);
                _this._markAllSubMeshesAsTexturesDirty();
                return deleted;
            };
        };
        /**
         * Get one of the submaterial by its index in the submaterials array
         * @param index The index to look the sub material at
         * @returns The Material if the index has been defined
         */
        MultiMaterial.prototype.getSubMaterial = function (index) {
            if (index < 0 || index >= this.subMaterials.length) {
                return this.getScene().defaultMaterial;
            }
            return this.subMaterials[index];
        };
        /**
         * Get the list of active textures for the whole sub materials list.
         * @returns All the textures that will be used during the rendering
         */
        MultiMaterial.prototype.getActiveTextures = function () {
            var _a;
            return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
                if (subMaterial) {
                    return subMaterial.getActiveTextures();
                }
                else {
                    return [];
                }
            }));
        };
        /**
         * Gets the current class name of the material e.g. "MultiMaterial"
         * Mainly use in serialization.
         * @returns the class name
         */
        MultiMaterial.prototype.getClassName = function () {
            return "MultiMaterial";
        };
        /**
         * Checks if the material is ready to render the requested sub mesh
         * @param mesh Define the mesh the submesh belongs to
         * @param subMesh Define the sub mesh to look readyness for
         * @param useInstances Define whether or not the material is used with instances
         * @returns true if ready, otherwise false
         */
        MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
            for (var index = 0; index < this.subMaterials.length; index++) {
                var subMaterial = this.subMaterials[index];
                if (subMaterial) {
                    if (subMaterial.storeEffectOnSubMeshes) {
                        if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
                            return false;
                        }
                        continue;
                    }
                    if (!subMaterial.isReady(mesh)) {
                        return false;
                    }
                }
            }
            return true;
        };
        /**
         * Clones the current material and its related sub materials
         * @param name Define the name of the newly cloned material
         * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
         * @returns the cloned material
         */
        MultiMaterial.prototype.clone = function (name, cloneChildren) {
            var newMultiMaterial = new MultiMaterial(name, this.getScene());
            for (var index = 0; index < this.subMaterials.length; index++) {
                var subMaterial = null;
                var current = this.subMaterials[index];
                if (cloneChildren && current) {
                    subMaterial = current.clone(name + "-" + current.name);
                }
                else {
                    subMaterial = this.subMaterials[index];
                }
                newMultiMaterial.subMaterials.push(subMaterial);
            }
            return newMultiMaterial;
        };
        /**
         * Serializes the materials into a JSON representation.
         * @returns the JSON representation
         */
        MultiMaterial.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.id = this.id;
            if (BABYLON.Tags) {
                serializationObject.tags = BABYLON.Tags.GetTags(this);
            }
            serializationObject.materials = [];
            for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
                var subMat = this.subMaterials[matIndex];
                if (subMat) {
                    serializationObject.materials.push(subMat.id);
                }
                else {
                    serializationObject.materials.push(null);
                }
            }
            return serializationObject;
        };
        /**
         * Dispose the material and release its associated resources
         * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on)
         * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app)
         */
        MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            var index = scene.multiMaterials.indexOf(this);
            if (index >= 0) {
                scene.multiMaterials.splice(index, 1);
            }
            _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
        };
        return MultiMaterial;
    }(BABYLON.Material));
    BABYLON.MultiMaterial = MultiMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.multiMaterial.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the touch inputs to control the movement of a free camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraTouchInput = /** @class */ (function () {
        function FreeCameraTouchInput() {
            /**
             * Defines the touch sensibility for rotation.
             * The higher the faster.
             */
            this.touchAngularSensibility = 200000.0;
            /**
             * Defines the touch sensibility for move.
             * The higher the faster.
             */
            this.touchMoveSensibility = 250.0;
            this._offsetX = null;
            this._offsetY = null;
            this._pointerPressed = new Array();
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var previousPosition = null;
            if (this._pointerInput === undefined) {
                this._onLostFocus = function (evt) {
                    _this._offsetX = null;
                    _this._offsetY = null;
                };
                this._pointerInput = function (p, s) {
                    var evt = p.event;
                    if (evt.pointerType === "mouse") {
                        return;
                    }
                    if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                        _this._pointerPressed.push(evt.pointerId);
                        if (_this._pointerPressed.length !== 1) {
                            return;
                        }
                        previousPosition = {
                            x: evt.clientX,
                            y: evt.clientY
                        };
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                        var index = _this._pointerPressed.indexOf(evt.pointerId);
                        if (index === -1) {
                            return;
                        }
                        _this._pointerPressed.splice(index, 1);
                        if (index != 0) {
                            return;
                        }
                        previousPosition = null;
                        _this._offsetX = null;
                        _this._offsetY = null;
                    }
                    else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
                        if (!noPreventDefault) {
                            evt.preventDefault();
                        }
                        if (!previousPosition) {
                            return;
                        }
                        var index = _this._pointerPressed.indexOf(evt.pointerId);
                        if (index != 0) {
                            return;
                        }
                        _this._offsetX = evt.clientX - previousPosition.x;
                        _this._offsetY = -(evt.clientY - previousPosition.y);
                    }
                };
            }
            this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
            if (this._onLostFocus) {
                element.addEventListener("blur", this._onLostFocus);
            }
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCameraTouchInput.prototype.detachControl = function (element) {
            if (this._pointerInput && element) {
                if (this._observer) {
                    this.camera.getScene().onPointerObservable.remove(this._observer);
                    this._observer = null;
                }
                if (this._onLostFocus) {
                    element.removeEventListener("blur", this._onLostFocus);
                    this._onLostFocus = null;
                }
                this._pointerPressed = [];
                this._offsetX = null;
                this._offsetY = null;
            }
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        FreeCameraTouchInput.prototype.checkInputs = function () {
            if (this._offsetX && this._offsetY) {
                var camera = this.camera;
                camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
                if (this._pointerPressed.length > 1) {
                    camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
                }
                else {
                    var speed = camera._computeLocalCameraSpeed();
                    var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
                    BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
                    camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
                }
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        FreeCameraTouchInput.prototype.getClassName = function () {
            return "FreeCameraTouchInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        FreeCameraTouchInput.prototype.getSimpleName = function () {
            return "touch";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
        return FreeCameraTouchInput;
    }());
    BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
    BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraTouchInput.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
        return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * This represents a FPS type of camera controlled by touch.
     * This is like a universal camera minus the Gamepad controls.
     * @see http://doc.babylonjs.com/features/cameras#universal-camera
     */
    var TouchCamera = /** @class */ (function (_super) {
        __extends(TouchCamera, _super);
        /**
         * Instantiates a new touch camera.
         * This represents a FPS type of camera controlled by touch.
         * This is like a universal camera minus the Gamepad controls.
         * @see http://doc.babylonjs.com/features/cameras#universal-camera
         * @param name Define the name of the camera in the scene
         * @param position Define the start position of the camera in the scene
         * @param scene Define the scene the camera belongs to
         */
        function TouchCamera(name, position, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.inputs.addTouch();
            _this._setupInputs();
            return _this;
        }
        Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
            /**
             * Defines the touch sensibility for rotation.
             * The higher the faster.
             */
            get: function () {
                var touch = this.inputs.attached["touch"];
                if (touch) {
                    return touch.touchAngularSensibility;
                }
                return 0;
            },
            set: function (value) {
                var touch = this.inputs.attached["touch"];
                if (touch) {
                    touch.touchAngularSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
            /**
             * Defines the touch sensibility for move.
             * The higher the faster.
             */
            get: function () {
                var touch = this.inputs.attached["touch"];
                if (touch) {
                    return touch.touchMoveSensibility;
                }
                return 0;
            },
            set: function (value) {
                var touch = this.inputs.attached["touch"];
                if (touch) {
                    touch.touchMoveSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the current object class name.
         * @return the class name
         */
        TouchCamera.prototype.getClassName = function () {
            return "TouchCamera";
        };
        /** @hidden */
        TouchCamera.prototype._setupInputs = function () {
            var mouse = this.inputs.attached["mouse"];
            if (mouse) {
                mouse.touchEnabled = false;
            }
        };
        return TouchCamera;
    }(BABYLON.FreeCamera));
    BABYLON.TouchCamera = TouchCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.touchCamera.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
     * This is the base class of any Procedural texture and contains most of the shareable code.
     * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
     */
    var ProceduralTexture = /** @class */ (function (_super) {
        __extends(ProceduralTexture, _super);
        /**
         * Instantiates a new procedural texture.
         * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
         * This is the base class of any Procedural texture and contains most of the shareable code.
         * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
         * @param name  Define the name of the texture
         * @param size Define the size of the texture to create
         * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
         * @param scene Define the scene the texture belongs to
         * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
         * @param generateMipMaps Define if the texture should creates mip maps or not
         * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
         */
        function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
            if (fallbackTexture === void 0) { fallbackTexture = null; }
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (isCube === void 0) { isCube = false; }
            var _this = _super.call(this, null, scene, !generateMipMaps) || this;
            _this.isCube = isCube;
            /**
             * Define if the texture is enabled or not (disabled texture will not render)
             */
            _this.isEnabled = true;
            /**
             * Define if the texture must be cleared before rendering (default is true)
             */
            _this.autoClear = true;
            /**
             * Event raised when the texture is generated
             */
            _this.onGeneratedObservable = new BABYLON.Observable();
            /** @hidden */
            _this._textures = {};
            _this._currentRefreshId = -1;
            _this._refreshRate = 1;
            _this._vertexBuffers = {};
            _this._uniforms = new Array();
            _this._samplers = new Array();
            _this._floats = {};
            _this._ints = {};
            _this._floatsArrays = {};
            _this._colors3 = {};
            _this._colors4 = {};
            _this._vectors2 = {};
            _this._vectors3 = {};
            _this._matrices = {};
            _this._fallbackTextureUsed = false;
            _this._cachedDefines = "";
            _this._contentUpdateId = -1;
            scene = _this.getScene();
            var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
            if (!component) {
                component = new BABYLON.ProceduralTextureSceneComponent(scene);
                scene._addComponent(component);
            }
            scene.proceduralTextures.push(_this);
            _this._engine = scene.getEngine();
            _this.name = name;
            _this.isRenderTarget = true;
            _this._size = size;
            _this._generateMipMaps = generateMipMaps;
            _this.setFragment(fragment);
            _this._fallbackTexture = fallbackTexture;
            if (isCube) {
                _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
                _this.setFloat("face", 0);
            }
            else {
                _this._texture = _this._engine.createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, generateDepthBuffer: false, generateStencilBuffer: false });
            }
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            _this._createIndexBuffer();
            return _this;
        }
        /**
         * Gets texture content (Use this function wisely as reading from a texture can be slow)
         * @returns an ArrayBufferView (Uint8Array or Float32Array)
         */
        ProceduralTexture.prototype.getContent = function () {
            if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
                return this._contentData;
            }
            this._contentData = this.readPixels(0, 0, this._contentData);
            this._contentUpdateId = this._currentRefreshId;
            return this._contentData;
        };
        ProceduralTexture.prototype._createIndexBuffer = function () {
            var engine = this._engine;
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
        };
        /** @hidden */
        ProceduralTexture.prototype._rebuild = function () {
            var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vb) {
                vb._rebuild();
            }
            this._createIndexBuffer();
            if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
                this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
            }
        };
        /**
         * Resets the texture in order to recreate its associated resources.
         * This can be called in case of context loss
         */
        ProceduralTexture.prototype.reset = function () {
            if (this._effect === undefined) {
                return;
            }
            var engine = this._engine;
            engine._releaseEffect(this._effect);
        };
        ProceduralTexture.prototype._getDefines = function () {
            return "";
        };
        /**
         * Is the texture ready to be used ? (rendered at least once)
         * @returns true if ready, otherwise, false.
         */
        ProceduralTexture.prototype.isReady = function () {
            var _this = this;
            var engine = this._engine;
            var shaders;
            if (!this._fragment) {
                return false;
            }
            if (this._fallbackTextureUsed) {
                return true;
            }
            var defines = this._getDefines();
            if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
                return true;
            }
            if (this._fragment.fragmentElement !== undefined) {
                shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
            }
            else {
                shaders = { vertex: "procedural", fragment: this._fragment };
            }
            this._cachedDefines = defines;
            this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
                _this.releaseInternalTexture();
                if (_this._fallbackTexture) {
                    _this._texture = _this._fallbackTexture._texture;
                    if (_this._texture) {
                        _this._texture.incrementReferences();
                    }
                }
                _this._fallbackTextureUsed = true;
            });
            return this._effect.isReady();
        };
        /**
         * Resets the refresh counter of the texture and start bak from scratch.
         * Could be usefull to regenerate the texture if it is setup to render only once.
         */
        ProceduralTexture.prototype.resetRefreshCounter = function () {
            this._currentRefreshId = -1;
        };
        /**
         * Set the fragment shader to use in order to render the texture.
         * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
         */
        ProceduralTexture.prototype.setFragment = function (fragment) {
            this._fragment = fragment;
        };
        Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
            /**
             * Define the refresh rate of the texture or the rendering frequency.
             * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
             */
            get: function () {
                return this._refreshRate;
            },
            set: function (value) {
                this._refreshRate = value;
                this.resetRefreshCounter();
            },
            enumerable: true,
            configurable: true
        });
        /** @hidden */
        ProceduralTexture.prototype._shouldRender = function () {
            if (!this.isEnabled || !this.isReady() || !this._texture) {
                if (this._texture) {
                    this._texture.isReady = false;
                }
                return false;
            }
            if (this._fallbackTextureUsed) {
                return false;
            }
            if (this._currentRefreshId === -1) { // At least render once
                this._currentRefreshId = 1;
                return true;
            }
            if (this.refreshRate === this._currentRefreshId) {
                this._currentRefreshId = 1;
                return true;
            }
            this._currentRefreshId++;
            return false;
        };
        /**
         * Get the size the texture is rendering at.
         * @returns the size (texture is always squared)
         */
        ProceduralTexture.prototype.getRenderSize = function () {
            return this._size;
        };
        /**
         * Resize the texture to new value.
         * @param size Define the new size the texture should have
         * @param generateMipMaps Define whether the new texture should create mip maps
         */
        ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
            if (this._fallbackTextureUsed) {
                return;
            }
            this.releaseInternalTexture();
            this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
            // Update properties
            this._size = size;
            this._generateMipMaps = generateMipMaps;
        };
        ProceduralTexture.prototype._checkUniform = function (uniformName) {
            if (this._uniforms.indexOf(uniformName) === -1) {
                this._uniforms.push(uniformName);
            }
        };
        /**
         * Set a texture in the shader program used to render.
         * @param name Define the name of the uniform samplers as defined in the shader
         * @param texture Define the texture to bind to this sampler
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setTexture = function (name, texture) {
            if (this._samplers.indexOf(name) === -1) {
                this._samplers.push(name);
            }
            this._textures[name] = texture;
            return this;
        };
        /**
         * Set a float in the shader.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setFloat = function (name, value) {
            this._checkUniform(name);
            this._floats[name] = value;
            return this;
        };
        /**
         * Set a int in the shader.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setInt = function (name, value) {
            this._checkUniform(name);
            this._ints[name] = value;
            return this;
        };
        /**
         * Set an array of floats in the shader.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setFloats = function (name, value) {
            this._checkUniform(name);
            this._floatsArrays[name] = value;
            return this;
        };
        /**
         * Set a vec3 in the shader from a Color3.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setColor3 = function (name, value) {
            this._checkUniform(name);
            this._colors3[name] = value;
            return this;
        };
        /**
         * Set a vec4 in the shader from a Color4.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setColor4 = function (name, value) {
            this._checkUniform(name);
            this._colors4[name] = value;
            return this;
        };
        /**
         * Set a vec2 in the shader from a Vector2.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setVector2 = function (name, value) {
            this._checkUniform(name);
            this._vectors2[name] = value;
            return this;
        };
        /**
         * Set a vec3 in the shader from a Vector3.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setVector3 = function (name, value) {
            this._checkUniform(name);
            this._vectors3[name] = value;
            return this;
        };
        /**
         * Set a mat4 in the shader from a MAtrix.
         * @param name Define the name of the uniform as defined in the shader
         * @param value Define the value to give to the uniform
         * @return the texture itself allowing "fluent" like uniform updates
         */
        ProceduralTexture.prototype.setMatrix = function (name, value) {
            this._checkUniform(name);
            this._matrices[name] = value;
            return this;
        };
        /**
         * Render the texture to its associated render target.
         * @param useCameraPostProcess Define if camera post process should be applied to the texture
         */
        ProceduralTexture.prototype.render = function (useCameraPostProcess) {
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            var engine = this._engine;
            // Render
            engine.enableEffect(this._effect);
            engine.setState(false);
            // Texture
            for (var name in this._textures) {
                this._effect.setTexture(name, this._textures[name]);
            }
            // Float
            for (name in this._ints) {
                this._effect.setInt(name, this._ints[name]);
            }
            // Float
            for (name in this._floats) {
                this._effect.setFloat(name, this._floats[name]);
            }
            // Floats
            for (name in this._floatsArrays) {
                this._effect.setArray(name, this._floatsArrays[name]);
            }
            // Color3
            for (name in this._colors3) {
                this._effect.setColor3(name, this._colors3[name]);
            }
            // Color4
            for (name in this._colors4) {
                var color = this._colors4[name];
                this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
            }
            // Vector2
            for (name in this._vectors2) {
                this._effect.setVector2(name, this._vectors2[name]);
            }
            // Vector3
            for (name in this._vectors3) {
                this._effect.setVector3(name, this._vectors3[name]);
            }
            // Matrix
            for (name in this._matrices) {
                this._effect.setMatrix(name, this._matrices[name]);
            }
            if (!this._texture) {
                return;
            }
            if (this.isCube) {
                for (var face = 0; face < 6; face++) {
                    engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
                    // VBOs
                    engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
                    this._effect.setFloat("face", face);
                    // Clear
                    if (this.autoClear) {
                        engine.clear(scene.clearColor, true, false, false);
                    }
                    // Draw order
                    engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
                    // Mipmaps
                    if (face === 5) {
                        engine.generateMipMapsForCubemap(this._texture);
                    }
                }
            }
            else {
                engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
                // VBOs
                engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
                // Clear
                if (this.autoClear) {
                    engine.clear(scene.clearColor, true, false, false);
                }
                // Draw order
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
            }
            // Unbind
            engine.unBindFramebuffer(this._texture, this.isCube);
            if (this.onGenerated) {
                this.onGenerated();
            }
            this.onGeneratedObservable.notifyObservers(this);
        };
        /**
         * Clone the texture.
         * @returns the cloned texture
         */
        ProceduralTexture.prototype.clone = function () {
            var textureSize = this.getSize();
            var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
            // Base texture
            newTexture.hasAlpha = this.hasAlpha;
            newTexture.level = this.level;
            // RenderTarget Texture
            newTexture.coordinatesMode = this.coordinatesMode;
            return newTexture;
        };
        /**
         * Dispose the texture and release its asoociated resources.
         */
        ProceduralTexture.prototype.dispose = function () {
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            var index = scene.proceduralTextures.indexOf(this);
            if (index >= 0) {
                scene.proceduralTextures.splice(index, 1);
            }
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
                this._indexBuffer = null;
            }
            _super.prototype.dispose.call(this);
        };
        __decorate([
            BABYLON.serialize()
        ], ProceduralTexture.prototype, "isEnabled", void 0);
        __decorate([
            BABYLON.serialize()
        ], ProceduralTexture.prototype, "autoClear", void 0);
        __decorate([
            BABYLON.serialize()
        ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
        __decorate([
            BABYLON.serialize()
        ], ProceduralTexture.prototype, "_size", void 0);
        __decorate([
            BABYLON.serialize()
        ], ProceduralTexture.prototype, "refreshRate", null);
        return ProceduralTexture;
    }(BABYLON.Texture));
    BABYLON.ProceduralTexture = ProceduralTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.proceduralTexture.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
     * in a given scene.
     */
    var ProceduralTextureSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function ProceduralTextureSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
            this.scene = scene;
            this.scene.proceduralTextures = new Array();
            scene.layers = new Array();
        }
        /**
         * Registers the component in a given scene
         */
        ProceduralTextureSceneComponent.prototype.register = function () {
            this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        ProceduralTextureSceneComponent.prototype.rebuild = function () {
            // Nothing to do here.
        };
        /**
         * Disposes the component and the associated ressources.
         */
        ProceduralTextureSceneComponent.prototype.dispose = function () {
            // Nothing to do here.
        };
        ProceduralTextureSceneComponent.prototype._beforeClear = function () {
            if (this.scene.proceduralTexturesEnabled) {
                BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
                for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
                    var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
                    if (proceduralTexture._shouldRender()) {
                        proceduralTexture.render();
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
            }
        };
        return ProceduralTextureSceneComponent;
    }());
    BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
     * Custom Procedural textures are the easiest way to create your own procedural in your application.
     * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
     */
    var CustomProceduralTexture = /** @class */ (function (_super) {
        __extends(CustomProceduralTexture, _super);
        /**
         * Instantiates a new Custom Procedural Texture.
         * Procedural texturing is a way to programmatically create a texture. There are 2 types of procedural textures: code-only, and code that references some classic 2D images, sometimes called 'refMaps' or 'sampler' images.
         * Custom Procedural textures are the easiest way to create your own procedural in your application.
         * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
         * @param name Define the name of the texture
         * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
         * @param size Define the size of the texture to create
         * @param scene Define the scene the texture belongs to
         * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
         * @param generateMipMaps Define if the texture should creates mip maps or not
         */
        function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
            var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
            _this._animate = true;
            _this._time = 0;
            _this._texturePath = texturePath;
            //Try to load json
            _this._loadJson(texturePath);
            _this.refreshRate = 1;
            return _this;
        }
        CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
            var _this = this;
            var noConfigFile = function () {
                BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
                try {
                    _this.setFragment(_this._texturePath);
                }
                catch (ex) {
                    BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
                }
            };
            var configFileUrl = jsonUrl + "/config.json";
            var xhr = new XMLHttpRequest();
            xhr.open("GET", configFileUrl, true);
            xhr.addEventListener("load", function () {
                if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
                    try {
                        _this._config = JSON.parse(xhr.response);
                        _this.updateShaderUniforms();
                        _this.updateTextures();
                        _this.setFragment(_this._texturePath + "/custom");
                        _this._animate = _this._config.animate;
                        _this.refreshRate = _this._config.refreshrate;
                    }
                    catch (ex) {
                        noConfigFile();
                    }
                }
                else {
                    noConfigFile();
                }
            }, false);
            xhr.addEventListener("error", function () {
                noConfigFile();
            }, false);
            try {
                xhr.send();
            }
            catch (ex) {
                BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
            }
        };
        /**
         * Is the texture ready to be used ? (rendered at least once)
         * @returns true if ready, otherwise, false.
         */
        CustomProceduralTexture.prototype.isReady = function () {
            if (!_super.prototype.isReady.call(this)) {
                return false;
            }
            for (var name in this._textures) {
                var texture = this._textures[name];
                if (!texture.isReady()) {
                    return false;
                }
            }
            return true;
        };
        /**
         * Render the texture to its associated render target.
         * @param useCameraPostProcess Define if camera post process should be applied to the texture
         */
        CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
            var scene = this.getScene();
            if (this._animate && scene) {
                this._time += scene.getAnimationRatio() * 0.03;
                this.updateShaderUniforms();
            }
            _super.prototype.render.call(this, useCameraPostProcess);
        };
        /**
         * Update the list of dependant textures samplers in the shader.
         */
        CustomProceduralTexture.prototype.updateTextures = function () {
            for (var i = 0; i < this._config.sampler2Ds.length; i++) {
                this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
            }
        };
        /**
         * Update the uniform values of the procedural texture in the shader.
         */
        CustomProceduralTexture.prototype.updateShaderUniforms = function () {
            if (this._config) {
                for (var j = 0; j < this._config.uniforms.length; j++) {
                    var uniform = this._config.uniforms[j];
                    switch (uniform.type) {
                        case "float":
                            this.setFloat(uniform.name, uniform.value);
                            break;
                        case "color3":
                            this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
                            break;
                        case "color4":
                            this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
                            break;
                        case "vector2":
                            this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
                            break;
                        case "vector3":
                            this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
                            break;
                    }
                }
            }
            this.setFloat("time", this._time);
        };
        Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
            /**
             * Define if the texture animates or not.
             */
            get: function () {
                return this._animate;
            },
            set: function (value) {
                this._animate = value;
            },
            enumerable: true,
            configurable: true
        });
        return CustomProceduralTexture;
    }(BABYLON.ProceduralTexture));
    BABYLON.CustomProceduralTexture = CustomProceduralTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.customProceduralTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the gamepad inputs to control a free camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraGamepadInput = /** @class */ (function () {
        function FreeCameraGamepadInput() {
            /**
             * Defines the gamepad rotation sensiblity.
             * This is the threshold from when rotation starts to be accounted for to prevent jittering.
             */
            this.gamepadAngularSensibility = 200;
            /**
             * Defines the gamepad move sensiblity.
             * This is the threshold from when moving starts to be accounted for for to prevent jittering.
             */
            this.gamepadMoveSensibility = 40;
            this._cameraTransform = BABYLON.Matrix.Identity();
            this._deltaTransform = BABYLON.Vector3.Zero();
            this._vector3 = BABYLON.Vector3.Zero();
            this._vector2 = BABYLON.Vector2.Zero();
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var manager = this.camera.getScene().gamepadManager;
            this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
                if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
                    // prioritize XBOX gamepads.
                    if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
                        _this.gamepad = gamepad;
                    }
                }
            });
            this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
                if (_this.gamepad === gamepad) {
                    _this.gamepad = null;
                }
            });
            this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCameraGamepadInput.prototype.detachControl = function (element) {
            this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
            this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
            this.gamepad = null;
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        FreeCameraGamepadInput.prototype.checkInputs = function () {
            if (this.gamepad && this.gamepad.leftStick) {
                var camera = this.camera;
                var LSValues = this.gamepad.leftStick;
                var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
                var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
                LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
                LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
                var RSValues = this.gamepad.rightStick;
                if (RSValues) {
                    var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
                    var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
                    RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
                    RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
                }
                else {
                    RSValues = { x: 0, y: 0 };
                }
                if (!camera.rotationQuaternion) {
                    BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
                }
                else {
                    camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
                }
                var speed = camera._computeLocalCameraSpeed() * 50.0;
                this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
                BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
                camera.cameraDirection.addInPlace(this._deltaTransform);
                this._vector2.copyFromFloats(RSValues.y, RSValues.x);
                camera.cameraRotation.addInPlace(this._vector2);
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        FreeCameraGamepadInput.prototype.getClassName = function () {
            return "FreeCameraGamepadInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        FreeCameraGamepadInput.prototype.getSimpleName = function () {
            return "gamepad";
        };
        __decorate([
            BABYLON.serialize()
        ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
        return FreeCameraGamepadInput;
    }());
    BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
    BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraGamepadInput.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Manage the gamepad inputs to control an arc rotate camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var ArcRotateCameraGamepadInput = /** @class */ (function () {
        function ArcRotateCameraGamepadInput() {
            /**
             * Defines the gamepad rotation sensiblity.
             * This is the threshold from when rotation starts to be accounted for to prevent jittering.
             */
            this.gamepadRotationSensibility = 80;
            /**
             * Defines the gamepad move sensiblity.
             * This is the threshold from when moving starts to be accounted for for to prevent jittering.
             */
            this.gamepadMoveSensibility = 40;
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
            var _this = this;
            var manager = this.camera.getScene().gamepadManager;
            this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
                if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
                    // prioritize XBOX gamepads.
                    if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
                        _this.gamepad = gamepad;
                    }
                }
            });
            this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
                if (_this.gamepad === gamepad) {
                    _this.gamepad = null;
                }
            });
            this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
            this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
            this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
            this.gamepad = null;
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
            if (this.gamepad) {
                var camera = this.camera;
                var RSValues = this.gamepad.rightStick;
                if (RSValues) {
                    if (RSValues.x != 0) {
                        var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
                        if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
                            camera.inertialAlphaOffset += normalizedRX;
                        }
                    }
                    if (RSValues.y != 0) {
                        var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
                        if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
                            camera.inertialBetaOffset += normalizedRY;
                        }
                    }
                }
                var LSValues = this.gamepad.leftStick;
                if (LSValues && LSValues.y != 0) {
                    var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
                    if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
                        this.camera.inertialRadiusOffset -= normalizedLY;
                    }
                }
            }
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        ArcRotateCameraGamepadInput.prototype.getClassName = function () {
            return "ArcRotateCameraGamepadInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
            return "gamepad";
        };
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
        __decorate([
            BABYLON.serialize()
        ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
        return ArcRotateCameraGamepadInput;
    }());
    BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
    BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Manager for handling gamepads
     */
    var GamepadManager = /** @class */ (function () {
        /**
         * Initializes the gamepad manager
         * @param _scene BabylonJS scene
         */
        function GamepadManager(_scene) {
            var _this = this;
            this._scene = _scene;
            this._babylonGamepads = [];
            this._oneGamepadConnected = false;
            /** @hidden */
            this._isMonitoring = false;
            /**
             * observable to be triggered when the gamepad controller has been disconnected
             */
            this.onGamepadDisconnectedObservable = new BABYLON.Observable();
            if (!BABYLON.Tools.IsWindowObjectExist()) {
                this._gamepadEventSupported = false;
            }
            else {
                this._gamepadEventSupported = 'GamepadEvent' in window;
                this._gamepadSupport = (navigator.getGamepads ||
                    navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
            }
            this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
                // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
                for (var i in _this._babylonGamepads) {
                    var gamepad = _this._babylonGamepads[i];
                    if (gamepad && gamepad._isConnected) {
                        _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
                    }
                }
            });
            this._onGamepadConnectedEvent = function (evt) {
                var gamepad = evt.gamepad;
                if (gamepad.index in _this._babylonGamepads) {
                    if (_this._babylonGamepads[gamepad.index].isConnected) {
                        return;
                    }
                }
                var newGamepad;
                if (_this._babylonGamepads[gamepad.index]) {
                    newGamepad = _this._babylonGamepads[gamepad.index];
                    newGamepad.browserGamepad = gamepad;
                    newGamepad._isConnected = true;
                }
                else {
                    newGamepad = _this._addNewGamepad(gamepad);
                }
                _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
                _this._startMonitoringGamepads();
            };
            this._onGamepadDisconnectedEvent = function (evt) {
                var gamepad = evt.gamepad;
                // Remove the gamepad from the list of gamepads to monitor.
                for (var i in _this._babylonGamepads) {
                    if (_this._babylonGamepads[i].index === gamepad.index) {
                        var disconnectedGamepad = _this._babylonGamepads[i];
                        disconnectedGamepad._isConnected = false;
                        _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
                        break;
                    }
                }
            };
            if (this._gamepadSupport) {
                //first add already-connected gamepads
                this._updateGamepadObjects();
                if (this._babylonGamepads.length) {
                    this._startMonitoringGamepads();
                }
                // Checking if the gamepad connected event is supported (like in Firefox)
                if (this._gamepadEventSupported) {
                    window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
                    window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
                }
                else {
                    this._startMonitoringGamepads();
                }
            }
        }
        Object.defineProperty(GamepadManager.prototype, "gamepads", {
            /**
             * The gamepads in the game pad manager
             */
            get: function () {
                return this._babylonGamepads;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get the gamepad controllers based on type
         * @param type The type of gamepad controller
         * @returns Nullable gamepad
         */
        GamepadManager.prototype.getGamepadByType = function (type) {
            if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
            for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
                var gamepad = _a[_i];
                if (gamepad && gamepad.type === type) {
                    return gamepad;
                }
            }
            return null;
        };
        /**
         * Disposes the gamepad manager
         */
        GamepadManager.prototype.dispose = function () {
            if (this._gamepadEventSupported) {
                if (this._onGamepadConnectedEvent) {
                    window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
                }
                if (this._onGamepadDisconnectedEvent) {
                    window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
                }
                this._onGamepadConnectedEvent = null;
                this._onGamepadDisconnectedEvent = null;
            }
            this._babylonGamepads.forEach(function (gamepad) {
                gamepad.dispose();
            });
            this.onGamepadConnectedObservable.clear();
            this.onGamepadDisconnectedObservable.clear();
            this._oneGamepadConnected = false;
            this._stopMonitoringGamepads();
            this._babylonGamepads = [];
        };
        GamepadManager.prototype._addNewGamepad = function (gamepad) {
            if (!this._oneGamepadConnected) {
                this._oneGamepadConnected = true;
            }
            var newGamepad;
            var xboxOne = (gamepad.id.search("Xbox One") !== -1);
            if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
                newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
            }
            // if pose is supported, use the (WebVR) pose enabled controller
            else if (gamepad.pose) {
                newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
            }
            else {
                newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
            }
            this._babylonGamepads[newGamepad.index] = newGamepad;
            return newGamepad;
        };
        GamepadManager.prototype._startMonitoringGamepads = function () {
            if (!this._isMonitoring) {
                this._isMonitoring = true;
                //back-comp
                if (!this._scene) {
                    this._checkGamepadsStatus();
                }
            }
        };
        GamepadManager.prototype._stopMonitoringGamepads = function () {
            this._isMonitoring = false;
        };
        /** @hidden */
        GamepadManager.prototype._checkGamepadsStatus = function () {
            var _this = this;
            // Hack to be compatible Chrome
            this._updateGamepadObjects();
            for (var i in this._babylonGamepads) {
                var gamepad = this._babylonGamepads[i];
                if (!gamepad || !gamepad.isConnected) {
                    continue;
                }
                gamepad.update();
            }
            if (this._isMonitoring && !this._scene) {
                BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
            }
        };
        // This function is called only on Chrome, which does not properly support
        // connection/disconnection events and forces you to recopy again the gamepad object
        GamepadManager.prototype._updateGamepadObjects = function () {
            var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
            for (var i = 0; i < gamepads.length; i++) {
                var gamepad = gamepads[i];
                if (gamepad) {
                    if (!this._babylonGamepads[gamepad.index]) {
                        var newGamepad = this._addNewGamepad(gamepad);
                        this.onGamepadConnectedObservable.notifyObservers(newGamepad);
                    }
                    else {
                        // Forced to copy again this object for Chrome for unknown reason
                        this._babylonGamepads[i].browserGamepad = gamepad;
                        if (!this._babylonGamepads[i].isConnected) {
                            this._babylonGamepads[i]._isConnected = true;
                            this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
                        }
                    }
                }
            }
        };
        return GamepadManager;
    }());
    BABYLON.GamepadManager = GamepadManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gamepadManager.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Represents a gamepad control stick position
     */
    var StickValues = /** @class */ (function () {
        /**
         * Initializes the gamepad x and y control stick values
         * @param x The x component of the gamepad control stick value
         * @param y The y component of the gamepad control stick value
         */
        function StickValues(
        /**
         * The x component of the control stick
         */
        x, 
        /**
         * The y component of the control stick
         */
        y) {
            this.x = x;
            this.y = y;
        }
        return StickValues;
    }());
    BABYLON.StickValues = StickValues;
    /**
     * Represents a gamepad
     */
    var Gamepad = /** @class */ (function () {
        /**
         * Initializes the gamepad
         * @param id The id of the gamepad
         * @param index The index of the gamepad
         * @param browserGamepad The browser gamepad
         * @param leftStickX The x component of the left joystick
         * @param leftStickY The y component of the left joystick
         * @param rightStickX The x component of the right joystick
         * @param rightStickY The y component of the right joystick
         */
        function Gamepad(
        /**
         * The id of the gamepad
         */
        id, 
        /**
         * The index of the gamepad
         */
        index, 
        /**
         * The browser gamepad
         */
        browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
            if (leftStickX === void 0) { leftStickX = 0; }
            if (leftStickY === void 0) { leftStickY = 1; }
            if (rightStickX === void 0) { rightStickX = 2; }
            if (rightStickY === void 0) { rightStickY = 3; }
            this.id = id;
            this.index = index;
            this.browserGamepad = browserGamepad;
            this._leftStick = { x: 0, y: 0 };
            this._rightStick = { x: 0, y: 0 };
            /** @hidden */
            this._isConnected = true;
            /**
             * Specifies whether the left control stick should be Y-inverted
             */
            this._invertLeftStickY = false;
            this.type = Gamepad.GAMEPAD;
            this._leftStickAxisX = leftStickX;
            this._leftStickAxisY = leftStickY;
            this._rightStickAxisX = rightStickX;
            this._rightStickAxisY = rightStickY;
            if (this.browserGamepad.axes.length >= 2) {
                this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
            }
            if (this.browserGamepad.axes.length >= 4) {
                this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
            }
        }
        Object.defineProperty(Gamepad.prototype, "isConnected", {
            /**
             * Specifies if the gamepad has been connected
             */
            get: function () {
                return this._isConnected;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Callback triggered when the left joystick has changed
         * @param callback
         */
        Gamepad.prototype.onleftstickchanged = function (callback) {
            this._onleftstickchanged = callback;
        };
        /**
         * Callback triggered when the right joystick has changed
         * @param callback
         */
        Gamepad.prototype.onrightstickchanged = function (callback) {
            this._onrightstickchanged = callback;
        };
        Object.defineProperty(Gamepad.prototype, "leftStick", {
            /**
             * Gets the left joystick
             */
            get: function () {
                return this._leftStick;
            },
            /**
             * Sets the left joystick values
             */
            set: function (newValues) {
                if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
                    this._onleftstickchanged(newValues);
                }
                this._leftStick = newValues;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Gamepad.prototype, "rightStick", {
            /**
             * Gets the right joystick
             */
            get: function () {
                return this._rightStick;
            },
            /**
             * Sets the right joystick value
             */
            set: function (newValues) {
                if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
                    this._onrightstickchanged(newValues);
                }
                this._rightStick = newValues;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Updates the gamepad joystick positions
         */
        Gamepad.prototype.update = function () {
            if (this._leftStick) {
                this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
                if (this._invertLeftStickY) {
                    this.leftStick.y *= -1;
                }
            }
            if (this._rightStick) {
                this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
            }
        };
        /**
         * Disposes the gamepad
         */
        Gamepad.prototype.dispose = function () {
        };
        /**
         * Represents a gamepad controller
         */
        Gamepad.GAMEPAD = 0;
        /**
         * Represents a generic controller
         */
        Gamepad.GENERIC = 1;
        /**
         * Represents an XBox controller
         */
        Gamepad.XBOX = 2;
        /**
         * Represents a pose-enabled controller
         */
        Gamepad.POSE_ENABLED = 3;
        return Gamepad;
    }());
    BABYLON.Gamepad = Gamepad;
    /**
     * Represents a generic gamepad
     */
    var GenericPad = /** @class */ (function (_super) {
        __extends(GenericPad, _super);
        /**
         * Initializes the generic gamepad
         * @param id The id of the generic gamepad
         * @param index The index of the generic gamepad
         * @param browserGamepad The browser gamepad
         */
        function GenericPad(id, index, browserGamepad) {
            var _this = _super.call(this, id, index, browserGamepad) || this;
            /**
             * Observable triggered when a button has been pressed
             */
            _this.onButtonDownObservable = new BABYLON.Observable();
            /**
             * Observable triggered when a button has been released
             */
            _this.onButtonUpObservable = new BABYLON.Observable();
            _this.type = Gamepad.GENERIC;
            _this._buttons = new Array(browserGamepad.buttons.length);
            return _this;
        }
        /**
         * Callback triggered when a button has been pressed
         * @param callback Called when a button has been pressed
         */
        GenericPad.prototype.onbuttondown = function (callback) {
            this._onbuttondown = callback;
        };
        /**
         * Callback triggered when a button has been released
         * @param callback Called when a button has been released
         */
        GenericPad.prototype.onbuttonup = function (callback) {
            this._onbuttonup = callback;
        };
        GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
            if (newValue !== currentValue) {
                if (newValue === 1) {
                    if (this._onbuttondown) {
                        this._onbuttondown(buttonIndex);
                    }
                    this.onButtonDownObservable.notifyObservers(buttonIndex);
                }
                if (newValue === 0) {
                    if (this._onbuttonup) {
                        this._onbuttonup(buttonIndex);
                    }
                    this.onButtonUpObservable.notifyObservers(buttonIndex);
                }
            }
            return newValue;
        };
        /**
         * Updates the generic gamepad
         */
        GenericPad.prototype.update = function () {
            _super.prototype.update.call(this);
            for (var index = 0; index < this._buttons.length; index++) {
                this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
            }
        };
        /**
         * Disposes the generic gamepad
         */
        GenericPad.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.onButtonDownObservable.clear();
            this.onButtonUpObservable.clear();
        };
        return GenericPad;
    }(Gamepad));
    BABYLON.GenericPad = GenericPad;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gamepad.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Defines supported buttons for XBox360 compatible gamepads
     */
    var Xbox360Button;
    (function (Xbox360Button) {
        /** A */
        Xbox360Button[Xbox360Button["A"] = 0] = "A";
        /** B */
        Xbox360Button[Xbox360Button["B"] = 1] = "B";
        /** X */
        Xbox360Button[Xbox360Button["X"] = 2] = "X";
        /** Y */
        Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
        /** Start */
        Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
        /** Back */
        Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
        /** Left button */
        Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
        /** Right button */
        Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
        /** Left stick */
        Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
        /** Right stick */
        Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
    })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
    /** Defines values for XBox360 DPad  */
    var Xbox360Dpad;
    (function (Xbox360Dpad) {
        /** Up */
        Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
        /** Down */
        Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
        /** Left */
        Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
        /** Right */
        Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
    })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
    /**
     * Defines a XBox360 gamepad
     */
    var Xbox360Pad = /** @class */ (function (_super) {
        __extends(Xbox360Pad, _super);
        /**
         * Creates a new XBox360 gamepad object
         * @param id defines the id of this gamepad
         * @param index defines its index
         * @param gamepad defines the internal HTML gamepad object
         * @param xboxOne defines if it is a XBox One gamepad
         */
        function Xbox360Pad(id, index, gamepad, xboxOne) {
            if (xboxOne === void 0) { xboxOne = false; }
            var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
            _this._leftTrigger = 0;
            _this._rightTrigger = 0;
            /** Observable raised when a button is pressed */
            _this.onButtonDownObservable = new BABYLON.Observable();
            /** Observable raised when a button is released */
            _this.onButtonUpObservable = new BABYLON.Observable();
            /** Observable raised when a pad is pressed */
            _this.onPadDownObservable = new BABYLON.Observable();
            /** Observable raised when a pad is released */
            _this.onPadUpObservable = new BABYLON.Observable();
            _this._buttonA = 0;
            _this._buttonB = 0;
            _this._buttonX = 0;
            _this._buttonY = 0;
            _this._buttonBack = 0;
            _this._buttonStart = 0;
            _this._buttonLB = 0;
            _this._buttonRB = 0;
            _this._buttonLeftStick = 0;
            _this._buttonRightStick = 0;
            _this._dPadUp = 0;
            _this._dPadDown = 0;
            _this._dPadLeft = 0;
            _this._dPadRight = 0;
            _this._isXboxOnePad = false;
            _this.type = BABYLON.Gamepad.XBOX;
            _this._isXboxOnePad = xboxOne;
            return _this;
        }
        /**
         * Defines the callback to call when left trigger is pressed
         * @param callback defines the callback to use
         */
        Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
            this._onlefttriggerchanged = callback;
        };
        /**
         * Defines the callback to call when right trigger is pressed
         * @param callback defines the callback to use
         */
        Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
            this._onrighttriggerchanged = callback;
        };
        Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
            /**
             * Gets the left trigger value
             */
            get: function () {
                return this._leftTrigger;
            },
            /**
             * Sets the left trigger value
             */
            set: function (newValue) {
                if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
                    this._onlefttriggerchanged(newValue);
                }
                this._leftTrigger = newValue;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
            /**
             * Gets the right trigger value
             */
            get: function () {
                return this._rightTrigger;
            },
            /**
             * Sets the right trigger value
             */
            set: function (newValue) {
                if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
                    this._onrighttriggerchanged(newValue);
                }
                this._rightTrigger = newValue;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Defines the callback to call when a button is pressed
         * @param callback defines the callback to use
         */
        Xbox360Pad.prototype.onbuttondown = function (callback) {
            this._onbuttondown = callback;
        };
        /**
         * Defines the callback to call when a button is released
         * @param callback defines the callback to use
         */
        Xbox360Pad.prototype.onbuttonup = function (callback) {
            this._onbuttonup = callback;
        };
        /**
         * Defines the callback to call when a pad is pressed
         * @param callback defines the callback to use
         */
        Xbox360Pad.prototype.ondpaddown = function (callback) {
            this._ondpaddown = callback;
        };
        /**
         * Defines the callback to call when a pad is released
         * @param callback defines the callback to use
         */
        Xbox360Pad.prototype.ondpadup = function (callback) {
            this._ondpadup = callback;
        };
        Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
            if (newValue !== currentValue) {
                if (newValue === 1) {
                    if (this._onbuttondown) {
                        this._onbuttondown(buttonType);
                    }
                    this.onButtonDownObservable.notifyObservers(buttonType);
                }
                if (newValue === 0) {
                    if (this._onbuttonup) {
                        this._onbuttonup(buttonType);
                    }
                    this.onButtonUpObservable.notifyObservers(buttonType);
                }
            }
            return newValue;
        };
        Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
            if (newValue !== currentValue) {
                if (newValue === 1) {
                    if (this._ondpaddown) {
                        this._ondpaddown(buttonType);
                    }
                    this.onPadDownObservable.notifyObservers(buttonType);
                }
                if (newValue === 0) {
                    if (this._ondpadup) {
                        this._ondpadup(buttonType);
                    }
                    this.onPadUpObservable.notifyObservers(buttonType);
                }
            }
            return newValue;
        };
        Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
            /**
             * Gets the value of the `A` button
             */
            get: function () {
                return this._buttonA;
            },
            /**
             * Sets the value of the `A` button
             */
            set: function (value) {
                this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
            /**
             * Gets the value of the `B` button
             */
            get: function () {
                return this._buttonB;
            },
            /**
             * Sets the value of the `B` button
             */
            set: function (value) {
                this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
            /**
             * Gets the value of the `X` button
             */
            get: function () {
                return this._buttonX;
            },
            /**
             * Sets the value of the `X` button
             */
            set: function (value) {
                this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
            /**
             * Gets the value of the `Y` button
             */
            get: function () {
                return this._buttonY;
            },
            /**
             * Sets the value of the `Y` button
             */
            set: function (value) {
                this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
            /**
             * Gets the value of the `Start` button
             */
            get: function () {
                return this._buttonStart;
            },
            /**
             * Sets the value of the `Start` button
             */
            set: function (value) {
                this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
            /**
             * Gets the value of the `Back` button
             */
            get: function () {
                return this._buttonBack;
            },
            /**
             * Sets the value of the `Back` button
             */
            set: function (value) {
                this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
            /**
             * Gets the value of the `Left` button
             */
            get: function () {
                return this._buttonLB;
            },
            /**
             * Sets the value of the `Left` button
             */
            set: function (value) {
                this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
            /**
             * Gets the value of the `Right` button
             */
            get: function () {
                return this._buttonRB;
            },
            /**
             * Sets the value of the `Right` button
             */
            set: function (value) {
                this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
            /**
             * Gets the value of the Left joystick
             */
            get: function () {
                return this._buttonLeftStick;
            },
            /**
             * Sets the value of the Left joystick
             */
            set: function (value) {
                this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
            /**
             * Gets the value of the Right joystick
             */
            get: function () {
                return this._buttonRightStick;
            },
            /**
             * Sets the value of the Right joystick
             */
            set: function (value) {
                this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
            /**
             * Gets the value of D-pad up
             */
            get: function () {
                return this._dPadUp;
            },
            /**
             * Sets the value of D-pad up
             */
            set: function (value) {
                this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
            /**
             * Gets the value of D-pad down
             */
            get: function () {
                return this._dPadDown;
            },
            /**
             * Sets the value of D-pad down
             */
            set: function (value) {
                this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
            /**
             * Gets the value of D-pad left
             */
            get: function () {
                return this._dPadLeft;
            },
            /**
             * Sets the value of D-pad left
             */
            set: function (value) {
                this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
            /**
             * Gets the value of D-pad right
             */
            get: function () {
                return this._dPadRight;
            },
            /**
             * Sets the value of D-pad right
             */
            set: function (value) {
                this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Force the gamepad to synchronize with device values
         */
        Xbox360Pad.prototype.update = function () {
            _super.prototype.update.call(this);
            if (this._isXboxOnePad) {
                this.buttonA = this.browserGamepad.buttons[0].value;
                this.buttonB = this.browserGamepad.buttons[1].value;
                this.buttonX = this.browserGamepad.buttons[2].value;
                this.buttonY = this.browserGamepad.buttons[3].value;
                this.buttonLB = this.browserGamepad.buttons[4].value;
                this.buttonRB = this.browserGamepad.buttons[5].value;
                this.leftTrigger = this.browserGamepad.axes[2];
                this.rightTrigger = this.browserGamepad.axes[5];
                this.buttonBack = this.browserGamepad.buttons[9].value;
                this.buttonStart = this.browserGamepad.buttons[8].value;
                this.buttonLeftStick = this.browserGamepad.buttons[6].value;
                this.buttonRightStick = this.browserGamepad.buttons[7].value;
                this.dPadUp = this.browserGamepad.buttons[11].value;
                this.dPadDown = this.browserGamepad.buttons[12].value;
                this.dPadLeft = this.browserGamepad.buttons[13].value;
                this.dPadRight = this.browserGamepad.buttons[14].value;
            }
            else {
                this.buttonA = this.browserGamepad.buttons[0].value;
                this.buttonB = this.browserGamepad.buttons[1].value;
                this.buttonX = this.browserGamepad.buttons[2].value;
                this.buttonY = this.browserGamepad.buttons[3].value;
                this.buttonLB = this.browserGamepad.buttons[4].value;
                this.buttonRB = this.browserGamepad.buttons[5].value;
                this.leftTrigger = this.browserGamepad.buttons[6].value;
                this.rightTrigger = this.browserGamepad.buttons[7].value;
                this.buttonBack = this.browserGamepad.buttons[8].value;
                this.buttonStart = this.browserGamepad.buttons[9].value;
                this.buttonLeftStick = this.browserGamepad.buttons[10].value;
                this.buttonRightStick = this.browserGamepad.buttons[11].value;
                this.dPadUp = this.browserGamepad.buttons[12].value;
                this.dPadDown = this.browserGamepad.buttons[13].value;
                this.dPadLeft = this.browserGamepad.buttons[14].value;
                this.dPadRight = this.browserGamepad.buttons[15].value;
            }
        };
        /**
         * Disposes the gamepad
         */
        Xbox360Pad.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.onButtonDownObservable.clear();
            this.onButtonUpObservable.clear();
            this.onPadDownObservable.clear();
            this.onPadUpObservable.clear();
        };
        return Xbox360Pad;
    }(BABYLON.Gamepad));
    BABYLON.Xbox360Pad = Xbox360Pad;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.xboxGamepad.js.map


var BABYLON;
(function (BABYLON) {
    /**
    * Defines the types of pose enabled controllers that are supported
    */
    var PoseEnabledControllerType;
    (function (PoseEnabledControllerType) {
        /**
         * HTC Vive
         */
        PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
        /**
         * Oculus Rift
         */
        PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
        /**
         * Windows mixed reality
         */
        PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
        /**
         * Samsung gear VR
         */
        PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
        /**
         * Google Daydream
         */
        PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
        /**
         * Generic
         */
        PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
    })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
    /**
     * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
     */
    var PoseEnabledControllerHelper = /** @class */ (function () {
        function PoseEnabledControllerHelper() {
        }
        /**
         * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
         * @param vrGamepad the gamepad to initialized
         * @returns a vr controller of the type the gamepad identified as
         */
        PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
            // Oculus Touch
            if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
                return new BABYLON.OculusTouchController(vrGamepad);
            }
            // Windows Mixed Reality controllers
            else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
                return new BABYLON.WindowsMotionController(vrGamepad);
            }
            // HTC Vive
            else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
                return new BABYLON.ViveController(vrGamepad);
            }
            // Samsung/Oculus Gear VR or Oculus Go
            else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
                return new BABYLON.GearVRController(vrGamepad);
            }
            // Google Daydream
            else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
                return new BABYLON.DaydreamController(vrGamepad);
            }
            // Generic
            else {
                return new BABYLON.GenericController(vrGamepad);
            }
        };
        return PoseEnabledControllerHelper;
    }());
    BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
    /**
     * Defines the PoseEnabledController object that contains state of a vr capable controller
     */
    var PoseEnabledController = /** @class */ (function (_super) {
        __extends(PoseEnabledController, _super);
        /**
         * Creates a new PoseEnabledController from a gamepad
         * @param browserGamepad the gamepad that the PoseEnabledController should be created from
         */
        function PoseEnabledController(browserGamepad) {
            var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
            // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
            _this._deviceRoomPosition = BABYLON.Vector3.Zero();
            _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
            /**
             * The device position in babylon space
             */
            _this.devicePosition = BABYLON.Vector3.Zero();
            /**
             * The device rotation in babylon space
             */
            _this.deviceRotationQuaternion = new BABYLON.Quaternion();
            /**
             * The scale factor of the device in babylon space
             */
            _this.deviceScaleFactor = 1;
            // Used to convert 6dof controllers to 3dof
            _this._trackPosition = true;
            _this._maxRotationDistFromHeadset = Math.PI / 5;
            _this._draggedRoomRotation = 0;
            _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
            /**
             * Internal, matrix used to convert room space to babylon space
             * @hidden
             */
            _this._deviceToWorld = BABYLON.Matrix.Identity();
            /**
             * Node to be used when casting a ray from the controller
             * @hidden
             */
            _this._pointingPoseNode = null;
            _this._workingMatrix = BABYLON.Matrix.Identity();
            /**
             * @hidden
             */
            _this._meshAttachedObservable = new BABYLON.Observable();
            _this.type = BABYLON.Gamepad.POSE_ENABLED;
            _this.controllerType = PoseEnabledControllerType.GENERIC;
            _this.position = BABYLON.Vector3.Zero();
            _this.rotationQuaternion = new BABYLON.Quaternion();
            _this._calculatedPosition = BABYLON.Vector3.Zero();
            _this._calculatedRotation = new BABYLON.Quaternion();
            BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
            return _this;
        }
        /**
         * @hidden
         */
        PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
            if (this._trackPosition) {
                this._calculatedPosition.copyFrom(fixedPosition);
                this._trackPosition = false;
            }
        };
        /**
         * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
         */
        PoseEnabledController.prototype.update = function () {
            _super.prototype.update.call(this);
            this._updatePoseAndMesh();
        };
        /**
         * Updates only the pose device and mesh without doing any button event checking
         */
        PoseEnabledController.prototype._updatePoseAndMesh = function () {
            var pose = this.browserGamepad.pose;
            this.updateFromDevice(pose);
            if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
                var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
                camera._computeDevicePosition();
                this._deviceToWorld.setTranslation(camera.devicePosition);
                if (camera.deviceRotationQuaternion) {
                    var camera = camera;
                    camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
                    // Find the radian distance away that the headset is from the controllers rotation
                    var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
                    if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
                        // Only rotate enouph to be within the _maxRotationDistFromHeadset
                        var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
                        this._draggedRoomRotation += rotationAmount;
                        // Rotate controller around headset
                        var sin = Math.sin(-rotationAmount);
                        var cos = Math.cos(-rotationAmount);
                        this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
                        this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
                    }
                }
            }
            BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
            this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
            BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
            this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
            if (this._mesh) {
                this._mesh.position.copyFrom(this.devicePosition);
                if (this._mesh.rotationQuaternion) {
                    this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
                }
            }
        };
        /**
         * Updates the state of the pose enbaled controller based on the raw pose data from the device
         * @param poseData raw pose fromthe device
         */
        PoseEnabledController.prototype.updateFromDevice = function (poseData) {
            if (poseData) {
                this.rawPose = poseData;
                if (poseData.position) {
                    this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
                    if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
                        this._deviceRoomPosition.z *= -1;
                    }
                    if (this._trackPosition) {
                        this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
                    }
                    this._calculatedPosition.addInPlace(this.position);
                }
                var pose = this.rawPose;
                if (poseData.orientation && pose.orientation) {
                    this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
                    if (this._mesh) {
                        if (this._mesh.getScene().useRightHandedSystem) {
                            this._deviceRoomRotationQuaternion.z *= -1;
                            this._deviceRoomRotationQuaternion.w *= -1;
                        }
                        else {
                            this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
                        }
                    }
                    // if the camera is set, rotate to the camera's rotation
                    this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
                }
            }
        };
        /**
         * Attaches a mesh to the controller
         * @param mesh the mesh to be attached
         */
        PoseEnabledController.prototype.attachToMesh = function (mesh) {
            if (this._mesh) {
                this._mesh.parent = null;
            }
            this._mesh = mesh;
            if (this._poseControlledCamera) {
                this._mesh.parent = this._poseControlledCamera;
            }
            if (!this._mesh.rotationQuaternion) {
                this._mesh.rotationQuaternion = new BABYLON.Quaternion();
            }
            // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
            this._updatePoseAndMesh();
            if (this._pointingPoseNode) {
                var parents = [];
                var obj = this._pointingPoseNode;
                while (obj.parent) {
                    parents.push(obj.parent);
                    obj = obj.parent;
                }
                parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
            }
            this._meshAttachedObservable.notifyObservers(mesh);
        };
        /**
         * Attaches the controllers mesh to a camera
         * @param camera the camera the mesh should be attached to
         */
        PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
            this._poseControlledCamera = camera;
            if (this._mesh) {
                this._mesh.parent = this._poseControlledCamera;
            }
        };
        /**
         * Disposes of the controller
         */
        PoseEnabledController.prototype.dispose = function () {
            if (this._mesh) {
                this._mesh.dispose();
            }
            this._mesh = null;
            _super.prototype.dispose.call(this);
        };
        Object.defineProperty(PoseEnabledController.prototype, "mesh", {
            /**
             * The mesh that is attached to the controller
             */
            get: function () {
                return this._mesh;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the ray of the controller in the direction the controller is pointing
         * @param length the length the resulting ray should be
         * @returns a ray in the direction the controller is pointing
         */
        PoseEnabledController.prototype.getForwardRay = function (length) {
            if (length === void 0) { length = 100; }
            if (!this.mesh) {
                return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
            }
            var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
            var origin = m.getTranslation();
            var forward = new BABYLON.Vector3(0, 0, -1);
            var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
            var direction = BABYLON.Vector3.Normalize(forwardWorld);
            return new BABYLON.Ray(origin, direction, length);
        };
        /**
         * Name of the child mesh that can be used to cast a ray from the controller
         */
        PoseEnabledController.POINTING_POSE = "POINTING_POSE";
        return PoseEnabledController;
    }(BABYLON.Gamepad));
    BABYLON.PoseEnabledController = PoseEnabledController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.poseEnabledController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Defines the WebVRController object that represents controllers tracked in 3D space
     */
    var WebVRController = /** @class */ (function (_super) {
        __extends(WebVRController, _super);
        /**
         * Creates a new WebVRController from a gamepad
         * @param vrGamepad the gamepad that the WebVRController should be created from
         */
        function WebVRController(vrGamepad) {
            var _this = _super.call(this, vrGamepad) || this;
            // Observables
            /**
             * Fired when the trigger state has changed
             */
            _this.onTriggerStateChangedObservable = new BABYLON.Observable();
            /**
             * Fired when the main button state has changed
             */
            _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
            /**
             * Fired when the secondary button state has changed
             */
            _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
            /**
             * Fired when the pad state has changed
             */
            _this.onPadStateChangedObservable = new BABYLON.Observable();
            /**
             * Fired when controllers stick values have changed
             */
            _this.onPadValuesChangedObservable = new BABYLON.Observable();
            /**
             * X and Y axis corrisponding to the controllers joystick
             */
            _this.pad = { x: 0, y: 0 };
            // avoid GC, store state in a tmp object
            _this._changes = {
                pressChanged: false,
                touchChanged: false,
                valueChanged: false,
                changed: false
            };
            _this._buttons = new Array(vrGamepad.buttons.length);
            _this.hand = vrGamepad.hand;
            return _this;
        }
        /**
         * Fired when a controller button's state has changed
         * @param callback the callback containing the button that was modified
         */
        WebVRController.prototype.onButtonStateChange = function (callback) {
            this._onButtonStateChange = callback;
        };
        Object.defineProperty(WebVRController.prototype, "defaultModel", {
            /**
             * The default controller model for the controller
             */
            get: function () {
                return this._defaultModel;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Updates the state of the controller and mesh based on the current position and rotation of the controller
         */
        WebVRController.prototype.update = function () {
            _super.prototype.update.call(this);
            for (var index = 0; index < this._buttons.length; index++) {
                this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
            }
            if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
                this.pad.x = this.leftStick.x;
                this.pad.y = this.leftStick.y;
                this.onPadValuesChangedObservable.notifyObservers(this.pad);
            }
        };
        WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
            if (!newState) {
                newState = {
                    pressed: false,
                    touched: false,
                    value: 0
                };
            }
            if (!currentState) {
                this._buttons[buttonIndex] = {
                    pressed: newState.pressed,
                    touched: newState.touched,
                    value: newState.value
                };
                return;
            }
            this._checkChanges(newState, currentState);
            if (this._changes.changed) {
                this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
                this._handleButtonChange(buttonIndex, newState, this._changes);
            }
            this._buttons[buttonIndex].pressed = newState.pressed;
            this._buttons[buttonIndex].touched = newState.touched;
            // oculus triggers are never 0, thou not touched.
            this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
        };
        WebVRController.prototype._checkChanges = function (newState, currentState) {
            this._changes.pressChanged = newState.pressed !== currentState.pressed;
            this._changes.touchChanged = newState.touched !== currentState.touched;
            this._changes.valueChanged = newState.value !== currentState.value;
            this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
            return this._changes;
        };
        /**
         * Disposes of th webVRCOntroller
         */
        WebVRController.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.onTriggerStateChangedObservable.clear();
            this.onMainButtonStateChangedObservable.clear();
            this.onSecondaryButtonStateChangedObservable.clear();
            this.onPadStateChangedObservable.clear();
            this.onPadValuesChangedObservable.clear();
        };
        return WebVRController;
    }(BABYLON.PoseEnabledController));
    BABYLON.WebVRController = WebVRController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.webVRController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Oculus Touch Controller
     */
    var OculusTouchController = /** @class */ (function (_super) {
        __extends(OculusTouchController, _super);
        /**
         * Creates a new OculusTouchController from a gamepad
         * @param vrGamepad the gamepad that the controller should be created from
         */
        function OculusTouchController(vrGamepad) {
            var _this = _super.call(this, vrGamepad) || this;
            /**
             * Fired when the secondary trigger on this controller is modified
             */
            _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
            /**
             * Fired when the thumb rest on this controller is modified
             */
            _this.onThumbRestChangedObservable = new BABYLON.Observable();
            _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
            return _this;
        }
        /**
         * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
         * @param scene scene in which to add meshes
         * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
         */
        OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
            var _this = this;
            var meshName;
            // Hand
            if (this.hand === 'left') {
                meshName = OculusTouchController.MODEL_LEFT_FILENAME;
            }
            else { // Right is the default if no hand is specified
                meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
            }
            BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
                /*
                Parent Mesh name: oculus_touch_left
                - body
                - trigger
                - thumbstick
                - grip
                - button_y
                - button_x
                - button_enter
                */
                _this._defaultModel = newMeshes[1];
                _this.attachToMesh(_this._defaultModel);
                if (meshLoaded) {
                    meshLoaded(_this._defaultModel);
                }
            });
        };
        Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
            /**
             * Fired when the A button on this controller is modified
             */
            get: function () {
                if (this.hand === 'right') {
                    return this.onMainButtonStateChangedObservable;
                }
                else {
                    throw new Error('No A button on left hand');
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
            /**
             * Fired when the B button on this controller is modified
             */
            get: function () {
                if (this.hand === 'right') {
                    return this.onSecondaryButtonStateChangedObservable;
                }
                else {
                    throw new Error('No B button on left hand');
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
            /**
             * Fired when the X button on this controller is modified
             */
            get: function () {
                if (this.hand === 'left') {
                    return this.onMainButtonStateChangedObservable;
                }
                else {
                    throw new Error('No X button on right hand');
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
            /**
             * Fired when the Y button on this controller is modified
             */
            get: function () {
                if (this.hand === 'left') {
                    return this.onSecondaryButtonStateChangedObservable;
                }
                else {
                    throw new Error('No Y button on right hand');
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
          * Called once for each button that changed state since the last frame
          * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
          * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
          * 2) secondary trigger (same)
          * 3) A (right) X (left), touch, pressed = value
          * 4) B / Y
          * 5) thumb rest
          * @param buttonIdx Which button index changed
          * @param state New state of the button
          * @param changes Which properties on the state changed since last frame
          */
        OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
            var notifyObject = state; //{ state: state, changes: changes };
            var triggerDirection = this.hand === 'right' ? -1 : 1;
            switch (buttonIdx) {
                case 0:
                    this.onPadStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 1: // index trigger
                    if (this._defaultModel) {
                        (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
                        (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
                        (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
                    }
                    this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 2: // secondary trigger
                    if (this._defaultModel) {
                        (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
                    }
                    this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 3:
                    if (this._defaultModel) {
                        if (notifyObject.pressed) {
                            (this._defaultModel.getChildren()[1]).position.y = -0.001;
                        }
                        else {
                            (this._defaultModel.getChildren()[1]).position.y = 0;
                        }
                    }
                    this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 4:
                    if (this._defaultModel) {
                        if (notifyObject.pressed) {
                            (this._defaultModel.getChildren()[2]).position.y = -0.001;
                        }
                        else {
                            (this._defaultModel.getChildren()[2]).position.y = 0;
                        }
                    }
                    this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 5:
                    this.onThumbRestChangedObservable.notifyObservers(notifyObject);
                    return;
            }
        };
        /**
         * Base Url for the controller model.
         */
        OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
        /**
         * File name for the left controller model.
         */
        OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
        /**
         * File name for the right controller model.
         */
        OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
        return OculusTouchController;
    }(BABYLON.WebVRController));
    BABYLON.OculusTouchController = OculusTouchController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.oculusTouchController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Vive Controller
     */
    var ViveController = /** @class */ (function (_super) {
        __extends(ViveController, _super);
        /**
         * Creates a new ViveController from a gamepad
         * @param vrGamepad the gamepad that the controller should be created from
         */
        function ViveController(vrGamepad) {
            var _this = _super.call(this, vrGamepad) || this;
            _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
            _this._invertLeftStickY = true;
            return _this;
        }
        /**
         * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
         * @param scene scene in which to add meshes
         * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
         */
        ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
            var _this = this;
            BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
                /*
                Parent Mesh name: ViveWand
                - body
                - r_gripper
                - l_gripper
                - menu_button
                - system_button
                - trackpad
                - trigger
                - LED
                */
                _this._defaultModel = newMeshes[1];
                _this.attachToMesh(_this._defaultModel);
                if (meshLoaded) {
                    meshLoaded(_this._defaultModel);
                }
            });
        };
        Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
            /**
             * Fired when the left button on this controller is modified
             */
            get: function () {
                return this.onMainButtonStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
            /**
             * Fired when the right button on this controller is modified
             */
            get: function () {
                return this.onMainButtonStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
            /**
             * Fired when the menu button on this controller is modified
             */
            get: function () {
                return this.onSecondaryButtonStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Called once for each button that changed state since the last frame
         * Vive mapping:
         * 0: touchpad
         * 1: trigger
         * 2: left AND right buttons
         * 3: menu button
         * @param buttonIdx Which button index changed
         * @param state New state of the button
         * @param changes Which properties on the state changed since last frame
         */
        ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
            var notifyObject = state; //{ state: state, changes: changes };
            switch (buttonIdx) {
                case 0:
                    this.onPadStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 1: // index trigger
                    if (this._defaultModel) {
                        (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
                    }
                    this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 2: // left AND right button
                    this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
                    return;
                case 3:
                    if (this._defaultModel) {
                        if (notifyObject.pressed) {
                            (this._defaultModel.getChildren()[2]).position.y = -0.001;
                        }
                        else {
                            (this._defaultModel.getChildren()[2]).position.y = 0;
                        }
                    }
                    this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
                    return;
            }
        };
        /**
         * Base Url for the controller model.
         */
        ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
        /**
         * File name for the controller model.
         */
        ViveController.MODEL_FILENAME = 'wand.babylon';
        return ViveController;
    }(BABYLON.WebVRController));
    BABYLON.ViveController = ViveController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.viveController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Generic Controller
     */
    var GenericController = /** @class */ (function (_super) {
        __extends(GenericController, _super);
        /**
         * Creates a new GenericController from a gamepad
         * @param vrGamepad the gamepad that the controller should be created from
         */
        function GenericController(vrGamepad) {
            return _super.call(this, vrGamepad) || this;
        }
        /**
         * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
         * @param scene scene in which to add meshes
         * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
         */
        GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
            var _this = this;
            BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
                _this._defaultModel = newMeshes[1];
                _this.attachToMesh(_this._defaultModel);
                if (meshLoaded) {
                    meshLoaded(_this._defaultModel);
                }
            });
        };
        /**
         * Called once for each button that changed state since the last frame
         * @param buttonIdx Which button index changed
         * @param state New state of the button
         * @param changes Which properties on the state changed since last frame
         */
        GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
            console.log("Button id: " + buttonIdx + "state: ");
            console.dir(state);
        };
        /**
         * Base Url for the controller model.
         */
        GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
        /**
         * File name for the controller model.
         */
        GenericController.MODEL_FILENAME = 'generic.babylon';
        return GenericController;
    }(BABYLON.WebVRController));
    BABYLON.GenericController = GenericController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.genericController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
     */
    var LoadedMeshInfo = /** @class */ (function () {
        function LoadedMeshInfo() {
            /**
             * Map of the button meshes contained in the controller
             */
            this.buttonMeshes = {};
            /**
             * Map of the axis meshes contained in the controller
             */
            this.axisMeshes = {};
        }
        return LoadedMeshInfo;
    }());
    /**
     * Defines the WindowsMotionController object that the state of the windows motion controller
     */
    var WindowsMotionController = /** @class */ (function (_super) {
        __extends(WindowsMotionController, _super);
        /**
         * Creates a new WindowsMotionController from a gamepad
         * @param vrGamepad the gamepad that the controller should be created from
         */
        function WindowsMotionController(vrGamepad) {
            var _this = _super.call(this, vrGamepad) || this;
            _this._mapping = {
                // Semantic button names
                buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
                // A mapping of the button name to glTF model node name
                // that should be transformed by button value.
                buttonMeshNames: {
                    'trigger': 'SELECT',
                    'menu': 'MENU',
                    'grip': 'GRASP',
                    'thumbstick': 'THUMBSTICK_PRESS',
                    'trackpad': 'TOUCHPAD_PRESS'
                },
                // This mapping is used to translate from the Motion Controller to Babylon semantics
                buttonObservableNames: {
                    'trigger': 'onTriggerStateChangedObservable',
                    'menu': 'onSecondaryButtonStateChangedObservable',
                    'grip': 'onMainButtonStateChangedObservable',
                    'thumbstick': 'onPadStateChangedObservable',
                    'trackpad': 'onTrackpadChangedObservable'
                },
                // A mapping of the axis name to glTF model node name
                // that should be transformed by axis value.
                // This array mirrors the browserGamepad.axes array, such that
                // the mesh corresponding to axis 0 is in this array index 0.
                axisMeshNames: [
                    'THUMBSTICK_X',
                    'THUMBSTICK_Y',
                    'TOUCHPAD_TOUCH_X',
                    'TOUCHPAD_TOUCH_Y'
                ],
                pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
            };
            /**
             * Fired when the trackpad on this controller is clicked
             */
            _this.onTrackpadChangedObservable = new BABYLON.Observable();
            /**
             * Fired when the trackpad on this controller is modified
             */
            _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
            /**
             * The current x and y values of this controller's trackpad
             */
            _this.trackpad = { x: 0, y: 0 };
            _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
            _this._loadedMeshInfo = null;
            return _this;
        }
        Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
            /**
             * Fired when the trigger on this controller is modified
             */
            get: function () {
                return this.onTriggerStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
            /**
             * Fired when the menu button on this controller is modified
             */
            get: function () {
                return this.onSecondaryButtonStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
            /**
             * Fired when the grip button on this controller is modified
             */
            get: function () {
                return this.onMainButtonStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
            /**
             * Fired when the thumbstick button on this controller is modified
             */
            get: function () {
                return this.onPadStateChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
            /**
             * Fired when the touchpad button on this controller is modified
             */
            get: function () {
                return this.onTrackpadChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
            /**
             * Fired when the touchpad values on this controller are modified
             */
            get: function () {
                return this.onTrackpadValuesChangedObservable;
            },
            enumerable: true,
            configurable: true
        });
        WindowsMotionController.prototype._updateTrackpad = function () {
            if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
                this.trackpad.x = this.browserGamepad["axes"][2];
                this.trackpad.y = this.browserGamepad["axes"][3];
                this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
            }
        };
        /**
         * Called once per frame by the engine.
         */
        WindowsMotionController.prototype.update = function () {
            _super.prototype.update.call(this);
            if (this.browserGamepad.axes) {
                this._updateTrackpad();
                // Only need to animate axes if there is a loaded mesh
                if (this._loadedMeshInfo) {
                    for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
                        this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
                    }
                }
            }
        };
        /**
         * Called once for each button that changed state since the last frame
         * @param buttonIdx Which button index changed
         * @param state New state of the button
         * @param changes Which properties on the state changed since last frame
         */
        WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
            var buttonName = this._mapping.buttons[buttonIdx];
            if (!buttonName) {
                return;
            }
            // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
            this._updateTrackpad();
            // Only emit events for buttons that we know how to map from index to name
            var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
            if (observable) {
                observable.notifyObservers(state);
            }
            this._lerpButtonTransform(buttonName, state.value);
        };
        /**
         * Moves the buttons on the controller mesh based on their current state
         * @param buttonName the name of the button to move
         * @param buttonValue the value of the button which determines the buttons new position
         */
        WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
            // If there is no loaded mesh, there is nothing to transform.
            if (!this._loadedMeshInfo) {
                return;
            }
            var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
            if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
                return;
            }
            BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
            BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
        };
        /**
         * Moves the axis on the controller mesh based on its current state
         * @param axis the index of the axis
         * @param axisValue the value of the axis which determines the meshes new position
         * @hidden
         */
        WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
            if (!this._loadedMeshInfo) {
                return;
            }
            var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
            if (!meshInfo) {
                return;
            }
            if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
                return;
            }
            // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
            var lerpValue = axisValue * 0.5 + 0.5;
            BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
            BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
        };
        /**
         * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
         * @param scene scene in which to add meshes
         * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
         */
        WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
            var _this = this;
            if (forceDefault === void 0) { forceDefault = false; }
            var path;
            var filename;
            // Checking if GLB loader is present
            if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
                // Determine the device specific folder based on the ID suffix
                var device = 'default';
                if (this.id && !forceDefault) {
                    var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
                    device = ((match && match[0]) || device);
                }
                // Hand
                if (this.hand === 'left') {
                    filename = WindowsMotionController.MODEL_LEFT_FILENAME;
                }
                else { // Right is the default if no hand is specified
                    filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
                }
                path = WindowsMotionController.MODEL_BASE_URL + device + '/';
            }
            else {
                BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
                path = BABYLON.GenericController.MODEL_BASE_URL;
                filename = BABYLON.GenericController.MODEL_FILENAME;
            }
            BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
                // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
                _this._loadedMeshInfo = _this.processModel(scene, meshes);
                if (!_this._loadedMeshInfo) {
                    return;
                }
                _this._defaultModel = _this._loadedMeshInfo.rootNode;
                _this.attachToMesh(_this._defaultModel);
                if (meshLoaded) {
                    meshLoaded(_this._defaultModel);
                }
            }, null, function (scene, message) {
                BABYLON.Tools.Log(message);
                BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
                if (!forceDefault) {
                    _this.initControllerMesh(scene, meshLoaded, true);
                }
            });
        };
        /**
         * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
         * can be transformed by button presses and axes values, based on this._mapping.
         *
         * @param scene scene in which the meshes exist
         * @param meshes list of meshes that make up the controller model to process
         * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
         */
        WindowsMotionController.prototype.processModel = function (scene, meshes) {
            var loadedMeshInfo = null;
            // Create a new mesh to contain the glTF hierarchy
            var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
            // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
            var childMesh = null;
            for (var i = 0; i < meshes.length; i++) {
                var mesh = meshes[i];
                if (!mesh.parent) {
                    // Exclude controller meshes from picking results
                    mesh.isPickable = false;
                    // Handle root node, attach to the new parentMesh
                    childMesh = mesh;
                    break;
                }
            }
            if (childMesh) {
                childMesh.setParent(parentMesh);
                // Create our mesh info. Note that this method will always return non-null.
                loadedMeshInfo = this.createMeshInfo(parentMesh);
            }
            else {
                BABYLON.Tools.Warn('Could not find root node in model file.');
            }
            return loadedMeshInfo;
        };
        WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
            var loadedMeshInfo = new LoadedMeshInfo();
            var i;
            loadedMeshInfo.rootNode = rootNode;
            // Reset the caches
            loadedMeshInfo.buttonMeshes = {};
            loadedMeshInfo.axisMeshes = {};
            // Button Meshes
            for (i = 0; i < this._mapping.buttons.length; i++) {
                var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
                if (!buttonMeshName) {
                    BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
                    continue;
                }
                var buttonMesh = getChildByName(rootNode, buttonMeshName);
                if (!buttonMesh) {
                    BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
                    continue;
                }
                var buttonMeshInfo = {
                    index: i,
                    value: getImmediateChildByName(buttonMesh, 'VALUE'),
                    pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
                    unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
                };
                if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
                    loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
                }
                else {
                    // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
                    BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
                        '(VALUE: ' + !!buttonMeshInfo.value +
                        ', PRESSED: ' + !!buttonMeshInfo.pressed +
                        ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
                        ')');
                }
            }
            // Axis Meshes
            for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
                var axisMeshName = this._mapping.axisMeshNames[i];
                if (!axisMeshName) {
                    BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
                    continue;
                }
                var axisMesh = getChildByName(rootNode, axisMeshName);
                if (!axisMesh) {
                    BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
                    continue;
                }
                var axisMeshInfo = {
                    index: i,
                    value: getImmediateChildByName(axisMesh, 'VALUE'),
                    min: getImmediateChildByName(axisMesh, 'MIN'),
                    max: getImmediateChildByName(axisMesh, 'MAX')
                };
                if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
                    loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
                }
                else {
                    // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
                    BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
                        '(VALUE: ' + !!axisMeshInfo.value +
                        ', MIN: ' + !!axisMeshInfo.min +
                        ', MAX:' + !!axisMeshInfo.max +
                        ')');
                }
            }
            // Pointing Ray
            loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
            if (!loadedMeshInfo.pointingPoseNode) {
                BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
            }
            else {
                this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
            }
            return loadedMeshInfo;
            // Look through all children recursively. This will return null if no mesh exists with the given name.
            function getChildByName(node, name) {
                return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
            }
            // Look through only immediate children. This will return null if no mesh exists with the given name.
            function getImmediateChildByName(node, name) {
                return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
            }
        };
        /**
         * Gets the ray of the controller in the direction the controller is pointing
         * @param length the length the resulting ray should be
         * @returns a ray in the direction the controller is pointing
         */
        WindowsMotionController.prototype.getForwardRay = function (length) {
            if (length === void 0) { length = 100; }
            if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
                return _super.prototype.getForwardRay.call(this, length);
            }
            var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
            var origin = m.getTranslation();
            var forward = new BABYLON.Vector3(0, 0, -1);
            var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
            var direction = BABYLON.Vector3.Normalize(forwardWorld);
            return new BABYLON.Ray(origin, direction, length);
        };
        /**
        * Disposes of the controller
        */
        WindowsMotionController.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this.onTrackpadChangedObservable.clear();
        };
        /**
         * The base url used to load the left and right controller models
         */
        WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
        /**
         * The name of the left controller model file
         */
        WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
        /**
         * The name of the right controller model file
         */
        WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
        /**
         * The controller name prefix for this controller type
         */
        WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
        /**
         * The controller id pattern for this controller type
         */
        WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
        return WindowsMotionController;
    }(BABYLON.WebVRController));
    BABYLON.WindowsMotionController = WindowsMotionController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.windowsMotionController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Gear VR Controller
     */
    var GearVRController = /** @class */ (function (_super) {
        __extends(GearVRController, _super);
        /**
         * Creates a new GearVRController from a gamepad
         * @param vrGamepad the gamepad that the controller should be created from
         */
        function GearVRController(vrGamepad) {
            var _this = _super.call(this, vrGamepad) || this;
            _this._buttonIndexToObservableNameMap = [
                'onTrackpadChangedObservable',
                'onTriggerStateChangedObservable' // Trigger
            ];
            _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
            // Initial starting position defaults to where hand would be (incase of only 3dof controller)
            _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
            _this._disableTrackPosition(_this._calculatedPosition);
            return _this;
        }
        /**
         * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
         * @param scene scene in which to add meshes
         * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
         */
        GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
            var _this = this;
            BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
                // Offset the controller so it will rotate around the users wrist
                var mesh = new BABYLON.Mesh("", scene);
                newMeshes[1].parent = mesh;
                newMeshes[1].position.z = -0.15;
                _this._defaultModel = mesh;
                _this.attachToMesh(_this._defaultModel);
                if (meshLoaded) {
                    meshLoaded(_this._defaultModel);
                }
            });
        };
        /**
         * Called once for each button that changed state since the last frame
         * @param buttonIdx Which button index changed
         * @param state New state of the button
         * @param changes Which properties on the state changed since last frame
         */
        GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
            if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
                var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
                // Only emit events for buttons that we know how to map from index to observable
                var observable = this[observableName];
                if (observable) {
                    observable.notifyObservers(state);
                }
            }
        };
        /**
         * Base Url for the controller model.
         */
        GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
        /**
         * File name for the controller model.
         */
        GearVRController.MODEL_FILENAME = 'generic.babylon';
        /**
         * Gamepad Id prefix used to identify this controller.
         */
        GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
        return GearVRController;
    }(BABYLON.WebVRController));
    BABYLON.GearVRController = GearVRController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gearVRController.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Google Daydream controller
     */
    var DaydreamController = /** @class */ (function (_super) {
        __extends(DaydreamController, _super);
        /**
         * Creates a new DaydreamController from a gamepad
         * @param vrGamepad the gamepad that the controller should be created from
         */
        function DaydreamController(vrGamepad) {
            var _this = _super.call(this, vrGamepad) || this;
            _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
            return _this;
        }
        /**
         * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
         * @param scene scene in which to add meshes
         * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
         */
        DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
            var _this = this;
            BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
                _this._defaultModel = newMeshes[1];
                _this.attachToMesh(_this._defaultModel);
                if (meshLoaded) {
                    meshLoaded(_this._defaultModel);
                }
            });
        };
        /**
         * Called once for each button that changed state since the last frame
         * @param buttonIdx Which button index changed
         * @param state New state of the button
         * @param changes Which properties on the state changed since last frame
         */
        DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
            // Daydream controller only has 1 GamepadButton (on the trackpad).
            if (buttonIdx === 0) {
                var observable = this.onTriggerStateChangedObservable;
                if (observable) {
                    observable.notifyObservers(state);
                }
            }
            else {
                // If the app or home buttons are ever made available
                BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
            }
        };
        /**
         * Base Url for the controller model.
         */
        DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
        /**
         * File name for the controller model.
         */
        DaydreamController.MODEL_FILENAME = 'generic.babylon';
        /**
         * Gamepad Id prefix used to identify Daydream Controller.
         */
        DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
        return DaydreamController;
    }(BABYLON.WebVRController));
    BABYLON.DaydreamController = DaydreamController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.daydreamController.js.map

var BABYLON;
(function (BABYLON) {
    Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
        get: function () {
            if (!this._gamepadManager) {
                this._gamepadManager = new BABYLON.GamepadManager(this);
                var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
                if (!component) {
                    component = new GamepadSystemSceneComponent(this);
                    this._addComponent(component);
                }
            }
            return this._gamepadManager;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Adds a gamepad to the free camera inputs manager
     */
    BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
        this.add(new BABYLON.FreeCameraGamepadInput());
        return this;
    };
    /**
     * Adds a gamepad to the arc rotate camera inputs manager
     */
    BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
        this.add(new BABYLON.ArcRotateCameraGamepadInput());
        return this;
    };
    /**
      * Defines the gamepad scene component responsible to manage gamepads in a given scene
      */
    var GamepadSystemSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function GamepadSystemSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
            this.scene = scene;
        }
        /**
         * Registers the component in a given scene
         */
        GamepadSystemSceneComponent.prototype.register = function () {
            this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        GamepadSystemSceneComponent.prototype.rebuild = function () {
            // Nothing to do for gamepads
        };
        /**
         * Disposes the component and the associated ressources
         */
        GamepadSystemSceneComponent.prototype.dispose = function () {
            var gamepadManager = this.scene._gamepadManager;
            if (gamepadManager) {
                gamepadManager.dispose();
                this.scene._gamepadManager = null;
            }
        };
        GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
            var gamepadManager = this.scene._gamepadManager;
            if (gamepadManager && gamepadManager._isMonitoring) {
                gamepadManager._checkGamepadsStatus();
            }
        };
        return GamepadSystemSceneComponent;
    }());
    BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gamepadSceneComponent.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
        return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
        return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
    });
    /**
     * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
     * an arc rotate version arcFollowCamera are available.
     * @see http://doc.babylonjs.com/features/cameras#follow-camera
     */
    var FollowCamera = /** @class */ (function (_super) {
        __extends(FollowCamera, _super);
        /**
         * Instantiates the follow camera.
         * @see http://doc.babylonjs.com/features/cameras#follow-camera
         * @param name Define the name of the camera in the scene
         * @param position Define the position of the camera
         * @param scene Define the scene the camera belong to
         * @param lockedTarget Define the target of the camera
         */
        function FollowCamera(name, position, scene, lockedTarget) {
            if (lockedTarget === void 0) { lockedTarget = null; }
            var _this = _super.call(this, name, position, scene) || this;
            /**
             * Distance the follow camera should follow an object at
             */
            _this.radius = 12;
            /**
             * Define a rotation offset between the camera and the object it follows
             */
            _this.rotationOffset = 0;
            /**
             * Define a height offset between the camera and the object it follows.
             * It can help following an object from the top (like a car chaing a plane)
             */
            _this.heightOffset = 4;
            /**
             * Define how fast the camera can accelerate to follow it s target.
             */
            _this.cameraAcceleration = 0.05;
            /**
             * Define the speed limit of the camera following an object.
             */
            _this.maxCameraSpeed = 20;
            _this.lockedTarget = lockedTarget;
            return _this;
        }
        FollowCamera.prototype._follow = function (cameraTarget) {
            if (!cameraTarget) {
                return;
            }
            var yRotation;
            if (cameraTarget.rotationQuaternion) {
                var rotMatrix = new BABYLON.Matrix();
                cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
                yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
            }
            else {
                yRotation = cameraTarget.rotation.y;
            }
            var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
            var targetPosition = cameraTarget.getAbsolutePosition();
            var targetX = targetPosition.x + Math.sin(radians) * this.radius;
            var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
            var dx = targetX - this.position.x;
            var dy = (targetPosition.y + this.heightOffset) - this.position.y;
            var dz = (targetZ) - this.position.z;
            var vx = dx * this.cameraAcceleration * 2; //this is set to .05
            var vy = dy * this.cameraAcceleration;
            var vz = dz * this.cameraAcceleration * 2;
            if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
                vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
            }
            if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
                vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
            }
            if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
                vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
            }
            this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
            this.setTarget(targetPosition);
        };
        /** @hidden */
        FollowCamera.prototype._checkInputs = function () {
            _super.prototype._checkInputs.call(this);
            if (this.lockedTarget) {
                this._follow(this.lockedTarget);
            }
        };
        /**
         * Gets the camera class name.
         * @returns the class name
         */
        FollowCamera.prototype.getClassName = function () {
            return "FollowCamera";
        };
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "radius", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "rotationOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "heightOffset", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "cameraAcceleration", void 0);
        __decorate([
            BABYLON.serialize()
        ], FollowCamera.prototype, "maxCameraSpeed", void 0);
        __decorate([
            BABYLON.serializeAsMeshReference("lockedTargetId")
        ], FollowCamera.prototype, "lockedTarget", void 0);
        return FollowCamera;
    }(BABYLON.TargetCamera));
    BABYLON.FollowCamera = FollowCamera;
    /**
     * Arc Rotate version of the follow camera.
     * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
     * @see http://doc.babylonjs.com/features/cameras#follow-camera
     */
    var ArcFollowCamera = /** @class */ (function (_super) {
        __extends(ArcFollowCamera, _super);
        /**
         * Instantiates a new ArcFollowCamera
         * @see http://doc.babylonjs.com/features/cameras#follow-camera
         * @param name Define the name of the camera
         * @param alpha Define the rotation angle of the camera around the logitudinal axis
         * @param beta Define the rotation angle of the camera around the elevation axis
         * @param radius Define the radius of the camera from its target point
         * @param target Define the target of the camera
         * @param scene Define the scene the camera belongs to
         */
        function ArcFollowCamera(name, 
        /** The longitudinal angle of the camera */
        alpha, 
        /** The latitudinal angle of the camera */
        beta, 
        /** The radius of the camera from its target */
        radius, 
        /** Define the camera target (the messh it should follow) */
        target, scene) {
            var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
            _this.alpha = alpha;
            _this.beta = beta;
            _this.radius = radius;
            _this.target = target;
            _this._cartesianCoordinates = BABYLON.Vector3.Zero();
            _this._follow();
            return _this;
        }
        ArcFollowCamera.prototype._follow = function () {
            if (!this.target) {
                return;
            }
            this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
            this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
            this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
            var targetPosition = this.target.getAbsolutePosition();
            this.position = targetPosition.add(this._cartesianCoordinates);
            this.setTarget(targetPosition);
        };
        /** @hidden */
        ArcFollowCamera.prototype._checkInputs = function () {
            _super.prototype._checkInputs.call(this);
            this._follow();
        };
        /**
         * Returns the class name of the object.
         * It is mostly used internally for serialization purposes.
         */
        ArcFollowCamera.prototype.getClassName = function () {
            return "ArcFollowCamera";
        };
        return ArcFollowCamera;
    }(BABYLON.TargetCamera));
    BABYLON.ArcFollowCamera = ArcFollowCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.followCamera.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
     * which still works and will still be found in many Playgrounds.
     * @see http://doc.babylonjs.com/features/cameras#universal-camera
     */
    var UniversalCamera = /** @class */ (function (_super) {
        __extends(UniversalCamera, _super);
        /**
         * The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
         * which still works and will still be found in many Playgrounds.
         * @see http://doc.babylonjs.com/features/cameras#universal-camera
         * @param name Define the name of the camera in the scene
         * @param position Define the start position of the camera in the scene
         * @param scene Define the scene the camera belongs to
         */
        function UniversalCamera(name, position, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.inputs.addGamepad();
            return _this;
        }
        Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
            /**
             * Defines the gamepad rotation sensiblity.
             * This is the threshold from when rotation starts to be accounted for to prevent jittering.
             */
            get: function () {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad) {
                    return gamepad.gamepadAngularSensibility;
                }
                return 0;
            },
            set: function (value) {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad) {
                    gamepad.gamepadAngularSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
            /**
             * Defines the gamepad move sensiblity.
             * This is the threshold from when moving starts to be accounted for for to prevent jittering.
             */
            get: function () {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad) {
                    return gamepad.gamepadMoveSensibility;
                }
                return 0;
            },
            set: function (value) {
                var gamepad = this.inputs.attached["gamepad"];
                if (gamepad) {
                    gamepad.gamepadMoveSensibility = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the current object class name.
         * @return the class name
         */
        UniversalCamera.prototype.getClassName = function () {
            return "UniversalCamera";
        };
        return UniversalCamera;
    }(BABYLON.TouchCamera));
    BABYLON.UniversalCamera = UniversalCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.universalCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
        return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * This represents a FPS type of camera. This is only here for back compat purpose.
     * Please use the UniversalCamera instead as both are identical.
     * @see http://doc.babylonjs.com/features/cameras#universal-camera
     */
    var GamepadCamera = /** @class */ (function (_super) {
        __extends(GamepadCamera, _super);
        /**
         * Instantiates a new Gamepad Camera
         * This represents a FPS type of camera. This is only here for back compat purpose.
         * Please use the UniversalCamera instead as both are identical.
         * @see http://doc.babylonjs.com/features/cameras#universal-camera
         * @param name Define the name of the camera in the scene
         * @param position Define the start position of the camera in the scene
         * @param scene Define the scene the camera belongs to
         */
        function GamepadCamera(name, position, scene) {
            return _super.call(this, name, position, scene) || this;
        }
        /**
         * Gets the current object class name.
         * @return the class name
         */
        GamepadCamera.prototype.getClassName = function () {
            return "GamepadCamera";
        };
        return GamepadCamera;
    }(BABYLON.UniversalCamera));
    BABYLON.GamepadCamera = GamepadCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gamepadCamera.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * PostProcessRenderPipelineManager class
     * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
     */
    var PostProcessRenderPipelineManager = /** @class */ (function () {
        /**
         * Initializes a PostProcessRenderPipelineManager
         * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
         */
        function PostProcessRenderPipelineManager() {
            this._renderPipelines = {};
        }
        /**
         * Adds a pipeline to the manager
         * @param renderPipeline The pipeline to add
         */
        PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
            this._renderPipelines[renderPipeline._name] = renderPipeline;
        };
        /**
         * Attaches a camera to the pipeline
         * @param renderPipelineName The name of the pipeline to attach to
         * @param cameras the camera to attach
         * @param unique if the camera can be attached multiple times to the pipeline
         */
        PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
            if (unique === void 0) { unique = false; }
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._attachCameras(cameras, unique);
        };
        /**
         * Detaches a camera from the pipeline
         * @param renderPipelineName The name of the pipeline to detach from
         * @param cameras the camera to detach
         */
        PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._detachCameras(cameras);
        };
        /**
         * Enables an effect by name on a pipeline
         * @param renderPipelineName the name of the pipeline to enable the effect in
         * @param renderEffectName the name of the effect to enable
         * @param cameras the cameras that the effect should be enabled on
         */
        PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._enableEffect(renderEffectName, cameras);
        };
        /**
         * Disables an effect by name on a pipeline
         * @param renderPipelineName the name of the pipeline to disable the effect in
         * @param renderEffectName the name of the effect to disable
         * @param cameras the cameras that the effect should be disabled on
         */
        PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
            var renderPipeline = this._renderPipelines[renderPipelineName];
            if (!renderPipeline) {
                return;
            }
            renderPipeline._disableEffect(renderEffectName, cameras);
        };
        /**
         * Updates the state of all contained render pipelines and disposes of any non supported pipelines
         */
        PostProcessRenderPipelineManager.prototype.update = function () {
            for (var renderPipelineName in this._renderPipelines) {
                if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
                    var pipeline = this._renderPipelines[renderPipelineName];
                    if (!pipeline.isSupported) {
                        pipeline.dispose();
                        delete this._renderPipelines[renderPipelineName];
                    }
                    else {
                        pipeline._update();
                    }
                }
            }
        };
        /** @hidden */
        PostProcessRenderPipelineManager.prototype._rebuild = function () {
            for (var renderPipelineName in this._renderPipelines) {
                if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
                    var pipeline = this._renderPipelines[renderPipelineName];
                    pipeline._rebuild();
                }
            }
        };
        /**
         * Disposes of the manager and pipelines
         */
        PostProcessRenderPipelineManager.prototype.dispose = function () {
            for (var renderPipelineName in this._renderPipelines) {
                if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
                    var pipeline = this._renderPipelines[renderPipelineName];
                    pipeline.dispose();
                }
            }
        };
        return PostProcessRenderPipelineManager;
    }());
    BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map

var BABYLON;
(function (BABYLON) {
    Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
        get: function () {
            if (!this._postProcessRenderPipelineManager) {
                // Register the G Buffer component to the scene.
                var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
                if (!component) {
                    component = new PostProcessRenderPipelineManagerSceneComponent(this);
                    this._addComponent(component);
                }
                this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
            }
            return this._postProcessRenderPipelineManager;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Defines the Render Pipeline scene component responsible to rendering pipelines
     */
    var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function PostProcessRenderPipelineManagerSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
            this.scene = scene;
        }
        /**
         * Registers the component in a given scene
         */
        PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
            this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
            if (this.scene._postProcessRenderPipelineManager) {
                this.scene._postProcessRenderPipelineManager._rebuild();
            }
        };
        /**
         * Disposes the component and the associated ressources
         */
        PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
            if (this.scene._postProcessRenderPipelineManager) {
                this.scene._postProcessRenderPipelineManager.dispose();
            }
        };
        PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
            if (this.scene._postProcessRenderPipelineManager) {
                this.scene._postProcessRenderPipelineManager.update();
            }
        };
        return PostProcessRenderPipelineManagerSceneComponent;
    }());
    BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents a set of one or more post processes in Babylon.
     * A post process can be used to apply a shader to a texture after it is rendered.
     * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
     */
    var PostProcessRenderEffect = /** @class */ (function () {
        /**
         * Instantiates a post process render effect.
         * A post process can be used to apply a shader to a texture after it is rendered.
         * @param engine The engine the effect is tied to
         * @param name The name of the effect
         * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
         * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
         */
        function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
            this._name = name;
            this._singleInstance = singleInstance || true;
            this._getPostProcesses = getPostProcesses;
            this._cameras = {};
            this._indicesForCamera = {};
            this._postProcesses = {};
        }
        Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
            /**
             * Checks if all the post processes in the effect are supported.
             */
            get: function () {
                for (var index in this._postProcesses) {
                    if (this._postProcesses.hasOwnProperty(index)) {
                        var pps = this._postProcesses[index];
                        for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
                            if (!pps[ppIndex].isSupported) {
                                return false;
                            }
                        }
                    }
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Updates the current state of the effect
         * @hidden
         */
        PostProcessRenderEffect.prototype._update = function () {
        };
        /**
         * Attaches the effect on cameras
         * @param cameras The camera to attach to.
         * @hidden
         */
        PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
            var _this = this;
            var cameraKey;
            var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
            if (!cams) {
                return;
            }
            for (var i = 0; i < cams.length; i++) {
                var camera = cams[i];
                var cameraName = camera.name;
                if (this._singleInstance) {
                    cameraKey = 0;
                }
                else {
                    cameraKey = cameraName;
                }
                if (!this._postProcesses[cameraKey]) {
                    var postProcess = this._getPostProcesses();
                    if (postProcess) {
                        this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
                    }
                }
                if (!this._indicesForCamera[cameraName]) {
                    this._indicesForCamera[cameraName] = [];
                }
                this._postProcesses[cameraKey].forEach(function (postProcess) {
                    var index = camera.attachPostProcess(postProcess);
                    _this._indicesForCamera[cameraName].push(index);
                });
                if (!this._cameras[cameraName]) {
                    this._cameras[cameraName] = camera;
                }
            }
        };
        /**
         * Detatches the effect on cameras
         * @param cameras The camera to detatch from.
         * @hidden
         */
        PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
            var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
            if (!cams) {
                return;
            }
            for (var i = 0; i < cams.length; i++) {
                var camera = cams[i];
                var cameraName = camera.name;
                this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
                    camera.detachPostProcess(postProcess);
                });
                if (this._cameras[cameraName]) {
                    //this._indicesForCamera.splice(index, 1);
                    this._cameras[cameraName] = null;
                }
            }
        };
        /**
         * Enables the effect on given cameras
         * @param cameras The camera to enable.
         * @hidden
         */
        PostProcessRenderEffect.prototype._enable = function (cameras) {
            var _this = this;
            var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
            if (!cams) {
                return;
            }
            for (var i = 0; i < cams.length; i++) {
                var camera = cams[i];
                var cameraName = camera.name;
                for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
                    if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
                        this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
                            cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
                        });
                    }
                }
            }
        };
        /**
         * Disables the effect on the given cameras
         * @param cameras The camera to disable.
         * @hidden
         */
        PostProcessRenderEffect.prototype._disable = function (cameras) {
            var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
            if (!cams) {
                return;
            }
            for (var i = 0; i < cams.length; i++) {
                var camera = cams[i];
                var cameraName = camera.name;
                this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
                    camera.detachPostProcess(postProcess);
                });
            }
        };
        /**
         * Gets a list of the post processes contained in the effect.
         * @param camera The camera to get the post processes on.
         * @returns The list of the post processes in the effect.
         */
        PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
            if (this._singleInstance) {
                return this._postProcesses[0];
            }
            else {
                if (!camera) {
                    return null;
                }
                return this._postProcesses[camera.name];
            }
        };
        return PostProcessRenderEffect;
    }());
    BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.postProcessRenderEffect.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * PostProcessRenderPipeline
     * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
     */
    var PostProcessRenderPipeline = /** @class */ (function () {
        /**
         * Initializes a PostProcessRenderPipeline
         * @param engine engine to add the pipeline to
         * @param name name of the pipeline
         */
        function PostProcessRenderPipeline(engine, name) {
            this.engine = engine;
            this._name = name;
            this._renderEffects = {};
            this._renderEffectsForIsolatedPass = new Array();
            this._cameras = [];
        }
        /**
         * "PostProcessRenderPipeline"
         * @returns "PostProcessRenderPipeline"
         */
        PostProcessRenderPipeline.prototype.getClassName = function () {
            return "PostProcessRenderPipeline";
        };
        Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
            /**
             * If all the render effects in the pipeline are support
             */
            get: function () {
                for (var renderEffectName in this._renderEffects) {
                    if (this._renderEffects.hasOwnProperty(renderEffectName)) {
                        if (!this._renderEffects[renderEffectName].isSupported) {
                            return false;
                        }
                    }
                }
                return true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Adds an effect to the pipeline
         * @param renderEffect the effect to add
         */
        PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
            this._renderEffects[renderEffect._name] = renderEffect;
        };
        // private
        /** @hidden */
        PostProcessRenderPipeline.prototype._rebuild = function () {
        };
        /** @hidden */
        PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
            var renderEffects = this._renderEffects[renderEffectName];
            if (!renderEffects) {
                return;
            }
            renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
        };
        /** @hidden */
        PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
            var renderEffects = this._renderEffects[renderEffectName];
            if (!renderEffects) {
                return;
            }
            renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
        };
        /** @hidden */
        PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
            var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
            if (!cams) {
                return;
            }
            var indicesToDelete = [];
            var i;
            for (i = 0; i < cams.length; i++) {
                var camera = cams[i];
                var cameraName = camera.name;
                if (this._cameras.indexOf(camera) === -1) {
                    this._cameras[cameraName] = camera;
                }
                else if (unique) {
                    indicesToDelete.push(i);
                }
            }
            for (i = 0; i < indicesToDelete.length; i++) {
                cameras.splice(indicesToDelete[i], 1);
            }
            for (var renderEffectName in this._renderEffects) {
                if (this._renderEffects.hasOwnProperty(renderEffectName)) {
                    this._renderEffects[renderEffectName]._attachCameras(cams);
                }
            }
        };
        /** @hidden */
        PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
            var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
            if (!cams) {
                return;
            }
            for (var renderEffectName in this._renderEffects) {
                if (this._renderEffects.hasOwnProperty(renderEffectName)) {
                    this._renderEffects[renderEffectName]._detachCameras(cams);
                }
            }
            for (var i = 0; i < cams.length; i++) {
                this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
            }
        };
        /** @hidden */
        PostProcessRenderPipeline.prototype._update = function () {
            for (var renderEffectName in this._renderEffects) {
                if (this._renderEffects.hasOwnProperty(renderEffectName)) {
                    this._renderEffects[renderEffectName]._update();
                }
            }
            for (var i = 0; i < this._cameras.length; i++) {
                var cameraName = this._cameras[i].name;
                if (this._renderEffectsForIsolatedPass[cameraName]) {
                    this._renderEffectsForIsolatedPass[cameraName]._update();
                }
            }
        };
        /** @hidden */
        PostProcessRenderPipeline.prototype._reset = function () {
            this._renderEffects = {};
            this._renderEffectsForIsolatedPass = new Array();
        };
        PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
            // Set samples of the very first post process to 4 to enable native anti-aliasing in browsers that support webGL 2.0 (See: https://github.com/BabylonJS/Babylon.js/issues/3754)
            var effectKeys = Object.keys(this._renderEffects);
            if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
                var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
                if (postProcesses) {
                    postProcesses[0].samples = sampleCount;
                    return true;
                }
            }
            return false;
        };
        /**
         * Disposes of the pipeline
         */
        PostProcessRenderPipeline.prototype.dispose = function () {
            // Must be implemented by children
        };
        __decorate([
            BABYLON.serialize()
        ], PostProcessRenderPipeline.prototype, "_name", void 0);
        return PostProcessRenderPipeline;
    }());
    BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.postProcessRenderPipeline.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents a depth renderer in Babylon.
     * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
     */
    var DepthRenderer = /** @class */ (function () {
        /**
         * Instantiates a depth renderer
         * @param scene The scene the renderer belongs to
         * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
         * @param camera The camera to be used to render the depth map (default: scene's active camera)
         */
        function DepthRenderer(scene, type, camera) {
            if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
            if (camera === void 0) { camera = null; }
            var _this = this;
            /**
             * Specifiess that the depth renderer will only be used within
             * the camera it is created for.
             * This can help forcing its rendering during the camera processing.
             */
            this.useOnlyInActiveCamera = false;
            this._scene = scene;
            // Register the G Buffer component to the scene.
            var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
            if (!component) {
                component = new BABYLON.DepthRendererSceneComponent(scene);
                scene._addComponent(component);
            }
            this._camera = camera;
            var engine = scene.getEngine();
            // Render target
            this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
            this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._depthMap.refreshRate = 1;
            this._depthMap.renderParticles = false;
            this._depthMap.renderList = null;
            // Camera to get depth map from to support multiple concurrent cameras
            this._depthMap.activeCamera = this._camera;
            this._depthMap.ignoreCameraViewport = true;
            this._depthMap.useCameraPostProcesses = false;
            // set default depth value to 1.0 (far away)
            this._depthMap.onClearObservable.add(function (engine) {
                engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
            });
            // Custom render function
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                var scene = _this._scene;
                var engine = scene.getEngine();
                var material = subMesh.getMaterial();
                if (!material) {
                    return;
                }
                // Culling and reverse (right handed system)
                engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
                var camera = _this._camera || scene.activeCamera;
                if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
                    engine.enableEffect(_this._effect);
                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
                    _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
                    _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
                    // Alpha test
                    if (material && material.needAlphaTesting()) {
                        var alphaTexture = material.getAlphaTestTexture();
                        if (alphaTexture) {
                            _this._effect.setTexture("diffuseSampler", alphaTexture);
                            _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                        }
                    }
                    // Bones
                    if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
                }
            };
            this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
                var index;
                if (depthOnlySubMeshes.length) {
                    engine.setColorWrite(false);
                    for (index = 0; index < depthOnlySubMeshes.length; index++) {
                        renderSubMesh(depthOnlySubMeshes.data[index]);
                    }
                    engine.setColorWrite(true);
                }
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
            };
        }
        /**
         * Creates the depth rendering effect and checks if the effect is ready.
         * @param subMesh The submesh to be used to render the depth map of
         * @param useInstances If multiple world instances should be used
         * @returns if the depth renderer is ready to render the depth map
         */
        DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
            var material = subMesh.getMaterial();
            if (material.disableDepthWrite) {
                return false;
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var mesh = subMesh.getMesh();
            // Alpha test
            if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
                defines.push("#define ALPHATEST");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                    defines.push("#define UV2");
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
            }
            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("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
            }
            return this._effect.isReady();
        };
        /**
         * Gets the texture which the depth map will be written to.
         * @returns The depth map texture
         */
        DepthRenderer.prototype.getDepthMap = function () {
            return this._depthMap;
        };
        /**
         * Disposes of the depth renderer.
         */
        DepthRenderer.prototype.dispose = function () {
            this._depthMap.dispose();
        };
        return DepthRenderer;
    }());
    BABYLON.DepthRenderer = DepthRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.depthRenderer.js.map

var BABYLON;
(function (BABYLON) {
    BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
        camera = camera || this.activeCamera;
        if (!camera) {
            throw "No camera available to enable depth renderer";
        }
        if (!this._depthRenderer) {
            this._depthRenderer = {};
        }
        if (!this._depthRenderer[camera.id]) {
            var textureType = 0;
            if (this.getEngine().getCaps().textureHalfFloatRender) {
                textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
            }
            else if (this.getEngine().getCaps().textureFloatRender) {
                textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
            }
            else {
                throw "Depth renderer does not support int texture type";
            }
            this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
        }
        return this._depthRenderer[camera.id];
    };
    BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
        camera = camera || this.activeCamera;
        if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
            return;
        }
        this._depthRenderer[camera.id].dispose();
        delete this._depthRenderer[camera.id];
    };
    /**
     * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
     * in several rendering techniques.
     */
    var DepthRendererSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function DepthRendererSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
            this.scene = scene;
        }
        /**
         * Registers the component in a given scene
         */
        DepthRendererSceneComponent.prototype.register = function () {
            this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
            this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        DepthRendererSceneComponent.prototype.rebuild = function () {
            // Nothing to do for this component
        };
        /**
         * Disposes the component and the associated ressources
         */
        DepthRendererSceneComponent.prototype.dispose = function () {
            for (var key in this.scene._depthRenderer) {
                this.scene._depthRenderer[key].dispose();
            }
        };
        DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
            if (this.scene._depthRenderer) {
                for (var key in this.scene._depthRenderer) {
                    var depthRenderer = this.scene._depthRenderer[key];
                    if (!depthRenderer.useOnlyInActiveCamera) {
                        renderTargets.push(depthRenderer.getDepthMap());
                    }
                }
            }
        };
        DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
            if (this.scene._depthRenderer) {
                for (var key in this.scene._depthRenderer) {
                    var depthRenderer = this.scene._depthRenderer[key];
                    if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
                        renderTargets.push(depthRenderer.getDepthMap());
                    }
                }
            }
        };
        return DepthRendererSceneComponent;
    }());
    BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.depthRendererSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This renderer is helpfull to fill one of the render target with a geometry buffer.
     */
    var GeometryBufferRenderer = /** @class */ (function () {
        /**
         * Creates a new G Buffer for the scene
         * @param scene The scene the buffer belongs to
         * @param ratio How big is the buffer related to the main canvas.
         */
        function GeometryBufferRenderer(scene, ratio) {
            if (ratio === void 0) { ratio = 1; }
            this._enablePosition = false;
            this._scene = scene;
            this._ratio = ratio;
            // Register the G Buffer component to the scene.
            var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
            if (!component) {
                component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
                scene._addComponent(component);
            }
            // Render target
            this._createRenderTargets();
        }
        Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
            /**
             * Set the render list (meshes to be rendered) used in the G buffer.
             */
            set: function (meshes) {
                this._multiRenderTarget.renderList = meshes;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
            /**
             * Gets wether or not G buffer are supported by the running hardware.
             * This requires draw buffer supports
             */
            get: function () {
                return this._multiRenderTarget.isSupported;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
            /**
             * Gets wether or not position are enabled for the G buffer.
             */
            get: function () {
                return this._enablePosition;
            },
            /**
             * Sets wether or not position are enabled for the G buffer.
             */
            set: function (enable) {
                this._enablePosition = enable;
                this.dispose();
                this._createRenderTargets();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
            /**
             * Gets the scene associated with the buffer.
             */
            get: function () {
                return this._scene;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
            /**
             * Gets the ratio used by the buffer during its creation.
             * How big is the buffer related to the main canvas.
             */
            get: function () {
                return this._ratio;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Checks wether everything is ready to render a submesh to the G buffer.
         * @param subMesh the submesh to check readiness for
         * @param useInstances is the mesh drawn using instance or not
         * @returns true if ready otherwise false
         */
        GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
            var material = subMesh.getMaterial();
            if (material && material.disableDepthWrite) {
                return false;
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
            var mesh = subMesh.getMesh();
            // Alpha test
            if (material && material.needAlphaTesting()) {
                defines.push("#define ALPHATEST");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                    defines.push("#define UV2");
                }
            }
            // Buffers
            if (this._enablePosition) {
                defines.push("#define POSITION");
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
            }
            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("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
            }
            return this._effect.isReady();
        };
        /**
         * Gets the current underlying G Buffer.
         * @returns the buffer
         */
        GeometryBufferRenderer.prototype.getGBuffer = function () {
            return this._multiRenderTarget;
        };
        Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
            /**
             * Gets the number of samples used to render the buffer (anti aliasing).
             */
            get: function () {
                return this._multiRenderTarget.samples;
            },
            /**
             * Sets the number of samples used to render the buffer (anti aliasing).
             */
            set: function (value) {
                this._multiRenderTarget.samples = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes the renderer and frees up associated resources.
         */
        GeometryBufferRenderer.prototype.dispose = function () {
            this.getGBuffer().dispose();
        };
        GeometryBufferRenderer.prototype._createRenderTargets = function () {
            var _this = this;
            var engine = this._scene.getEngine();
            var count = this._enablePosition ? 3 : 2;
            this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
            if (!this.isSupported) {
                return;
            }
            this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._multiRenderTarget.refreshRate = 1;
            this._multiRenderTarget.renderParticles = false;
            this._multiRenderTarget.renderList = null;
            // set default depth value to 1.0 (far away)
            this._multiRenderTarget.onClearObservable.add(function (engine) {
                engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
            });
            // Custom render function
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                var scene = _this._scene;
                var engine = scene.getEngine();
                var material = subMesh.getMaterial();
                if (!material) {
                    return;
                }
                // Culling
                engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
                if (_this.isReady(subMesh, hardwareInstancedRendering)) {
                    engine.enableEffect(_this._effect);
                    mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
                    _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
                    _this._effect.setMatrix("view", scene.getViewMatrix());
                    // Alpha test
                    if (material && material.needAlphaTesting()) {
                        var alphaTexture = material.getAlphaTestTexture();
                        if (alphaTexture) {
                            _this._effect.setTexture("diffuseSampler", alphaTexture);
                            _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                        }
                    }
                    // Bones
                    if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                        _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
                }
            };
            this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
                var index;
                if (depthOnlySubMeshes.length) {
                    engine.setColorWrite(false);
                    for (index = 0; index < depthOnlySubMeshes.length; index++) {
                        renderSubMesh(depthOnlySubMeshes.data[index]);
                    }
                    engine.setColorWrite(true);
                }
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
            };
        };
        return GeometryBufferRenderer;
    }());
    BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.geometryBufferRenderer.js.map

var BABYLON;
(function (BABYLON) {
    Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
        get: function () {
            this._geometryBufferRenderer;
        },
        set: function (value) {
            if (value && value.isSupported) {
                this._geometryBufferRenderer = value;
            }
        },
        enumerable: true,
        configurable: true
    });
    BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
        if (ratio === void 0) { ratio = 1; }
        if (this._geometryBufferRenderer) {
            return this._geometryBufferRenderer;
        }
        this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
        if (!this._geometryBufferRenderer.isSupported) {
            this._geometryBufferRenderer = null;
        }
        return this._geometryBufferRenderer;
    };
    BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
        if (!this._geometryBufferRenderer) {
            return;
        }
        this._geometryBufferRenderer.dispose();
        this._geometryBufferRenderer = null;
    };
    /**
     * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
     * in several rendering techniques.
     */
    var GeometryBufferRendererSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function GeometryBufferRendererSceneComponent(scene) {
            /**
             * The component name helpful to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
            this.scene = scene;
        }
        /**
         * Registers the component in a given scene
         */
        GeometryBufferRendererSceneComponent.prototype.register = function () {
            this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
            // Nothing to do for this component
        };
        /**
         * Disposes the component and the associated ressources
         */
        GeometryBufferRendererSceneComponent.prototype.dispose = function () {
            // Nothing to do for this component
        };
        GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
            if (this.scene._geometryBufferRenderer) {
                renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
            }
        };
        return GeometryBufferRendererSceneComponent;
    }());
    BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Render pipeline to produce ssao effect
     */
    var SSAORenderingPipeline = /** @class */ (function (_super) {
        __extends(SSAORenderingPipeline, _super);
        /**
         * @constructor
         * @param name - The rendering pipeline name
         * @param scene - The scene linked to this pipeline
         * @param ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
         * @param cameras - The array of cameras that the rendering pipeline will be attached to
         */
        function SSAORenderingPipeline(name, scene, ratio, cameras) {
            var _this = _super.call(this, scene.getEngine(), name) || this;
            // Members
            /**
             * @ignore
            * The PassPostProcess id in the pipeline that contains the original scene color
            */
            _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
            /**
             * @ignore
            * The SSAO PostProcess id in the pipeline
            */
            _this.SSAORenderEffect = "SSAORenderEffect";
            /**
             * @ignore
            * The horizontal blur PostProcess id in the pipeline
            */
            _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
            /**
             * @ignore
            * The vertical blur PostProcess id in the pipeline
            */
            _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
            /**
             * @ignore
            * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
            */
            _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
            /**
            * The output strength of the SSAO post-process. Default value is 1.0.
            */
            _this.totalStrength = 1.0;
            /**
            * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
            */
            _this.radius = 0.0001;
            /**
            * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
            * Must not be equal to fallOff and superior to fallOff.
            * Default value is 0.975
            */
            _this.area = 0.0075;
            /**
            * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
            * Must not be equal to area and inferior to area.
            * Default value is 0.0
            */
            _this.fallOff = 0.000001;
            /**
            * The base color of the SSAO post-process
            * The final result is "base + ssao" between [0, 1]
            */
            _this.base = 0.5;
            _this._firstUpdate = true;
            _this._scene = scene;
            // Set up assets
            _this._createRandomTexture();
            _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
            var ssaoRatio = ratio.ssaoRatio || ratio;
            var combineRatio = ratio.combineRatio || ratio;
            _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
            _this._createSSAOPostProcess(ssaoRatio);
            _this._createBlurPostProcess(ssaoRatio);
            _this._createSSAOCombinePostProcess(combineRatio);
            // Set up pipeline
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(_this);
            if (cameras) {
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
            }
            return _this;
        }
        // Public Methods
        /**
         * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
         */
        SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
            if (disableDepthRender === void 0) { disableDepthRender = false; }
            for (var i = 0; i < this._scene.cameras.length; i++) {
                var camera = this._scene.cameras[i];
                this._originalColorPostProcess.dispose(camera);
                this._ssaoPostProcess.dispose(camera);
                this._blurHPostProcess.dispose(camera);
                this._blurVPostProcess.dispose(camera);
                this._ssaoCombinePostProcess.dispose(camera);
            }
            this._randomTexture.dispose();
            if (disableDepthRender) {
                this._scene.disableDepthRenderer();
            }
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
            _super.prototype.dispose.call(this);
        };
        // Private Methods
        SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
            var _this = this;
            var size = 16;
            this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._blurHPostProcess.onActivateObservable.add(function () {
                var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
                _this._blurHPostProcess.kernel = size * dw;
            });
            this._blurVPostProcess.onActivateObservable.add(function () {
                var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
                _this._blurVPostProcess.kernel = size * dw;
            });
        };
        /** @hidden */
        SSAORenderingPipeline.prototype._rebuild = function () {
            this._firstUpdate = true;
            _super.prototype._rebuild.call(this);
        };
        SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
            var _this = this;
            var numSamples = 16;
            var sampleSphere = [
                0.5381, 0.1856, -0.4319,
                0.1379, 0.2486, 0.4430,
                0.3371, 0.5679, -0.0057,
                -0.6999, -0.0451, -0.0019,
                0.0689, -0.1598, -0.8547,
                0.0560, 0.0069, -0.1843,
                -0.0146, 0.1402, 0.0762,
                0.0100, -0.1924, -0.0344,
                -0.3577, -0.5301, -0.4358,
                -0.3169, 0.1063, 0.0158,
                0.0103, -0.5869, 0.0046,
                -0.0897, -0.4940, 0.3287,
                0.7119, -0.0154, -0.0918,
                -0.0533, 0.0596, -0.5411,
                0.0352, -0.0631, 0.5460,
                -0.4776, 0.2847, -0.0271
            ];
            var samplesFactor = 1.0 / numSamples;
            this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
                "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
                "area", "fallOff", "base", "range", "viewport"
            ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
            this._ssaoPostProcess.onApply = function (effect) {
                if (_this._firstUpdate) {
                    effect.setArray3("sampleSphere", sampleSphere);
                    effect.setFloat("samplesFactor", samplesFactor);
                    effect.setFloat("randTextureTiles", 4.0);
                }
                effect.setFloat("totalStrength", _this.totalStrength);
                effect.setFloat("radius", _this.radius);
                effect.setFloat("area", _this.area);
                effect.setFloat("fallOff", _this.fallOff);
                effect.setFloat("base", _this.base);
                effect.setTexture("textureSampler", _this._depthTexture);
                effect.setTexture("randomSampler", _this._randomTexture);
            };
        };
        SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
            var _this = this;
            this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._ssaoCombinePostProcess.onApply = function (effect) {
                effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
                effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
            };
        };
        SSAORenderingPipeline.prototype._createRandomTexture = function () {
            var size = 512;
            this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            var context = this._randomTexture.getContext();
            var rand = function (min, max) {
                return Math.random() * (max - min) + min;
            };
            var randVector = BABYLON.Vector3.Zero();
            for (var x = 0; x < size; x++) {
                for (var y = 0; y < size; y++) {
                    randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
                    randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
                    randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
                    context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
                    context.fillRect(x, y, 1, 1);
                }
            }
            this._randomTexture.update(false);
        };
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "radius", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "area", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "fallOff", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAORenderingPipeline.prototype, "base", void 0);
        return SSAORenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Render pipeline to produce ssao effect
     */
    var SSAO2RenderingPipeline = /** @class */ (function (_super) {
        __extends(SSAO2RenderingPipeline, _super);
        /**
         * @constructor
         * @param name The rendering pipeline name
         * @param scene The scene linked to this pipeline
         * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
         * @param cameras The array of cameras that the rendering pipeline will be attached to
         */
        function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
            var _this = _super.call(this, scene.getEngine(), name) || this;
            // Members
            /**
             * @ignore
            * The PassPostProcess id in the pipeline that contains the original scene color
            */
            _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
            /**
             * @ignore
            * The SSAO PostProcess id in the pipeline
            */
            _this.SSAORenderEffect = "SSAORenderEffect";
            /**
             * @ignore
            * The horizontal blur PostProcess id in the pipeline
            */
            _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
            /**
             * @ignore
            * The vertical blur PostProcess id in the pipeline
            */
            _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
            /**
             * @ignore
            * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
            */
            _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
            /**
            * The output strength of the SSAO post-process. Default value is 1.0.
            */
            _this.totalStrength = 1.0;
            /**
            * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
            */
            _this.maxZ = 100.0;
            /**
            * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
            */
            _this.minZAspect = 0.2;
            _this._samples = 8;
            _this._textureSamples = 1;
            _this._expensiveBlur = true;
            /**
            * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
            */
            _this.radius = 2.0;
            /**
            * The base color of the SSAO post-process
            * The final result is "base + ssao" between [0, 1]
            */
            _this.base = 0;
            _this._firstUpdate = true;
            _this._bits = new Uint32Array(1);
            _this._scene = scene;
            _this._ratio = ratio;
            if (!_this.isSupported) {
                BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
                return _this;
            }
            var ssaoRatio = _this._ratio.ssaoRatio || ratio;
            var blurRatio = _this._ratio.blurRatio || ratio;
            // Set up assets
            var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
            _this._createRandomTexture();
            _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
            _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
            _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
            _this._originalColorPostProcess.samples = _this.textureSamples;
            _this._createSSAOPostProcess(1.0);
            _this._createBlurPostProcess(ssaoRatio, blurRatio);
            _this._createSSAOCombinePostProcess(blurRatio);
            // Set up pipeline
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(_this);
            if (cameras) {
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
            }
            return _this;
        }
        Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
            get: function () {
                return this._samples;
            },
            /**
            * Number of samples used for the SSAO calculations. Default value is 8
            */
            set: function (n) {
                this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
                this._samples = n;
                this._sampleSphere = this._generateHemisphere();
                this._firstUpdate = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
            get: function () {
                return this._textureSamples;
            },
            /**
            * Number of samples to use for antialiasing
            */
            set: function (n) {
                this._textureSamples = n;
                this._originalColorPostProcess.samples = n;
                this._blurHPostProcess.samples = n;
                this._blurVPostProcess.samples = n;
                this._ssaoPostProcess.samples = n;
                this._ssaoCombinePostProcess.samples = n;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
            get: function () {
                return this._expensiveBlur;
            },
            /**
            * If bilateral blur should be used
            */
            set: function (b) {
                this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
                this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
                this._expensiveBlur = b;
                this._firstUpdate = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
            /**
            *  Support test.
            */
            get: function () {
                var engine = BABYLON.Engine.LastCreatedEngine;
                if (!engine) {
                    return false;
                }
                return engine.getCaps().drawBuffersExtension;
            },
            enumerable: true,
            configurable: true
        });
        // Public Methods
        /**
         * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
         */
        SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
            if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
            for (var i = 0; i < this._scene.cameras.length; i++) {
                var camera = this._scene.cameras[i];
                this._originalColorPostProcess.dispose(camera);
                this._ssaoPostProcess.dispose(camera);
                this._blurHPostProcess.dispose(camera);
                this._blurVPostProcess.dispose(camera);
                this._ssaoCombinePostProcess.dispose(camera);
            }
            this._randomTexture.dispose();
            if (disableGeometryBufferRenderer) {
                this._scene.disableGeometryBufferRenderer();
            }
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
            _super.prototype.dispose.call(this);
        };
        // Private Methods
        SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
            var _this = this;
            this._samplerOffsets = [];
            var expensive = this.expensiveBlur;
            for (var i = -8; i < 8; i++) {
                this._samplerOffsets.push(i * 2 + 0.5);
            }
            this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
            this._blurHPostProcess.onApply = function (effect) {
                if (!_this._scene.activeCamera) {
                    return;
                }
                effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
                effect.setFloat("near", _this._scene.activeCamera.minZ);
                effect.setFloat("far", _this._scene.activeCamera.maxZ);
                effect.setFloat("radius", _this.radius);
                effect.setTexture("depthSampler", _this._depthTexture);
                if (_this._firstUpdate) {
                    effect.setArray("samplerOffsets", _this._samplerOffsets);
                }
            };
            this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
            this._blurVPostProcess.onApply = function (effect) {
                if (!_this._scene.activeCamera) {
                    return;
                }
                effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
                effect.setFloat("near", _this._scene.activeCamera.minZ);
                effect.setFloat("far", _this._scene.activeCamera.maxZ);
                effect.setFloat("radius", _this.radius);
                effect.setTexture("depthSampler", _this._depthTexture);
                if (_this._firstUpdate) {
                    effect.setArray("samplerOffsets", _this._samplerOffsets);
                    _this._firstUpdate = false;
                }
            };
            this._blurHPostProcess.samples = this.textureSamples;
            this._blurVPostProcess.samples = this.textureSamples;
        };
        /** @hidden */
        SSAO2RenderingPipeline.prototype._rebuild = function () {
            this._firstUpdate = true;
            _super.prototype._rebuild.call(this);
        };
        //Van der Corput radical inverse
        SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
            this._bits[0] = i;
            this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
            this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
            this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
            this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
            this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
            return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
        };
        SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
            return [i / n, this._radicalInverse_VdC(i)];
        };
        SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
            var phi = v * 2.0 * Math.PI;
            // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
            var cosTheta = 1.0 - (u * 0.85 + 0.15);
            var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
            return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
        };
        SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
            var numSamples = this.samples;
            var result = [];
            var vector;
            var i = 0;
            while (i < numSamples) {
                if (numSamples < 16) {
                    vector = this._hemisphereSample_uniform(Math.random(), Math.random());
                }
                else {
                    var rand = this._hammersley(i, numSamples);
                    vector = this._hemisphereSample_uniform(rand[0], rand[1]);
                }
                result.push(vector.x, vector.y, vector.z);
                i++;
            }
            return result;
        };
        SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
            var _this = this;
            var numSamples = this.samples;
            this._sampleSphere = this._generateHemisphere();
            this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
                "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
                "base", "range", "projection", "near", "far", "texelSize",
                "xViewport", "yViewport", "maxZ", "minZAspect"
            ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
            this._ssaoPostProcess.onApply = function (effect) {
                if (_this._firstUpdate) {
                    effect.setArray3("sampleSphere", _this._sampleSphere);
                    effect.setFloat("randTextureTiles", 32.0);
                }
                if (!_this._scene.activeCamera) {
                    return;
                }
                effect.setFloat("samplesFactor", 1 / _this.samples);
                effect.setFloat("totalStrength", _this.totalStrength);
                effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
                effect.setFloat("radius", _this.radius);
                effect.setFloat("maxZ", _this.maxZ);
                effect.setFloat("minZAspect", _this.minZAspect);
                effect.setFloat("base", _this.base);
                effect.setFloat("near", _this._scene.activeCamera.minZ);
                effect.setFloat("far", _this._scene.activeCamera.maxZ);
                effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
                effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
                effect.setMatrix("projection", _this._scene.getProjectionMatrix());
                effect.setTexture("textureSampler", _this._depthTexture);
                effect.setTexture("normalSampler", _this._normalTexture);
                effect.setTexture("randomSampler", _this._randomTexture);
            };
            this._ssaoPostProcess.samples = this.textureSamples;
        };
        SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
            var _this = this;
            this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._ssaoCombinePostProcess.onApply = function (effect) {
                var viewport = _this._scene.activeCamera.viewport;
                effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
                effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
            };
            this._ssaoCombinePostProcess.samples = this.textureSamples;
        };
        SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
            var size = 128;
            this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            var context = this._randomTexture.getContext();
            var rand = function (min, max) {
                return Math.random() * (max - min) + min;
            };
            var randVector = BABYLON.Vector3.Zero();
            for (var x = 0; x < size; x++) {
                for (var y = 0; y < size; y++) {
                    randVector.x = rand(0.0, 1.0);
                    randVector.y = rand(0.0, 1.0);
                    randVector.z = 0.0;
                    randVector.normalize();
                    randVector.scaleInPlace(255);
                    randVector.x = Math.floor(randVector.x);
                    randVector.y = Math.floor(randVector.y);
                    context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
                    context.fillRect(x, y, 1, 1);
                }
            }
            this._randomTexture.update(false);
        };
        /**
         * Serialize the rendering pipeline (Used when exporting)
         * @returns the serialized object
         */
        SSAO2RenderingPipeline.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "SSAO2RenderingPipeline";
            return serializationObject;
        };
        /**
         * Parse the serialized pipeline
         * @param source Source pipeline.
         * @param scene The scene to load the pipeline to.
         * @param rootUrl The URL of the serialized pipeline.
         * @returns An instantiated pipeline from the serialized object.
         */
        SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
        };
        __decorate([
            BABYLON.serialize()
        ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
        __decorate([
            BABYLON.serialize("samples")
        ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
        __decorate([
            BABYLON.serialize("textureSamples")
        ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
        __decorate([
            BABYLON.serialize("expensiveBlur")
        ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAO2RenderingPipeline.prototype, "radius", void 0);
        __decorate([
            BABYLON.serialize()
        ], SSAO2RenderingPipeline.prototype, "base", void 0);
        return SSAO2RenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * BABYLON.JS Chromatic Aberration GLSL Shader
     * Author: Olivier Guyot
     * Separates very slightly R, G and B colors on the edges of the screen
     * Inspired by Francois Tarlier & Martins Upitis
     */
    var LensRenderingPipeline = /** @class */ (function (_super) {
        __extends(LensRenderingPipeline, _super);
        /**
         * @constructor
         *
         * Effect parameters are as follow:
         * {
         *      chromatic_aberration: number;       // from 0 to x (1 for realism)
         *      edge_blur: number;                  // from 0 to x (1 for realism)
         *      distortion: number;                 // from 0 to x (1 for realism)
         *      grain_amount: number;               // from 0 to 1
         *      grain_texture: BABYLON.Texture;     // texture to use for grain effect; if unset, use random B&W noise
         *      dof_focus_distance: number;         // depth-of-field: focus distance; unset to disable (disabled by default)
         *      dof_aperture: number;               // depth-of-field: focus blur bias (default: 1)
         *      dof_darken: number;                 // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
         *      dof_pentagon: boolean;              // depth-of-field: makes a pentagon-like "bokeh" effect
         *      dof_gain: number;                   // depth-of-field: highlights gain; unset to disable (disabled by default)
         *      dof_threshold: number;              // depth-of-field: highlights threshold (default: 1)
         *      blur_noise: boolean;                // add a little bit of noise to the blur (default: true)
         * }
         * Note: if an effect parameter is unset, effect is disabled
         *
         * @param name The rendering pipeline name
         * @param parameters - An object containing all parameters (see above)
         * @param scene The scene linked to this pipeline
         * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param cameras The array of cameras that the rendering pipeline will be attached to
         */
        function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
            if (ratio === void 0) { ratio = 1.0; }
            var _this = _super.call(this, scene.getEngine(), name) || this;
            // Lens effects can be of the following:
            // - chromatic aberration (slight shift of RGB colors)
            // - blur on the edge of the lens
            // - lens distortion
            // - depth-of-field blur & highlights enhancing
            // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
            // - grain effect (noise or custom texture)
            // Two additional texture samplers are needed:
            // - depth map (for depth-of-field)
            // - grain texture
            /**
             * @ignore
             * The chromatic aberration PostProcess id in the pipeline
             */
            _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
            /**
             * @ignore
             * The highlights enhancing PostProcess id in the pipeline
             */
            _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
            /**
             * @ignore
            * The depth-of-field PostProcess id in the pipeline
            */
            _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
            _this._scene = scene;
            // Fetch texture samplers
            _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
            if (parameters.grain_texture) {
                _this._grainTexture = parameters.grain_texture;
            }
            else {
                _this._createGrainTexture();
            }
            // save parameters
            _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
            _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
            _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
            _this._distortion = parameters.distortion ? parameters.distortion : 0;
            _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
            _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
            _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
            _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
            _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
            _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
            _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
            // Create effects
            _this._createChromaticAberrationPostProcess(ratio);
            _this._createHighlightsPostProcess(ratio);
            _this._createDepthOfFieldPostProcess(ratio / 4);
            // Set up pipeline
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
            _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
            if (_this._highlightsGain === -1) {
                _this._disableEffect(_this.HighlightsEnhancingEffect, null);
            }
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(_this);
            if (cameras) {
                scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
            }
            return _this;
        }
        // public methods (self explanatory)
        /**
         * Sets the amount of blur at the edges
         * @param amount blur amount
         */
        LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
        /**
         * Sets edge blur to 0
         */
        LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
        /**
         * Sets the amout of grain
         * @param amount Amount of grain
         */
        LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
        /**
         * Set grain amount to 0
         */
        LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
        /**
         * Sets the chromatic aberration amount
         * @param amount amount of chromatic aberration
         */
        LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
        /**
         * Sets chromatic aberration amount to 0
         */
        LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
        /**
         * Sets the EdgeDistortion amount
         * @param amount amount of EdgeDistortion
         */
        LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
        /**
         * Sets edge distortion to 0
         */
        LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
        /**
         * Sets the FocusDistance amount
         * @param amount amount of FocusDistance
         */
        LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
        /**
        * Disables depth of field
        */
        LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
        /**
         * Sets the Aperture amount
         * @param amount amount of Aperture
         */
        LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
        /**
         * Sets the DarkenOutOfFocus amount
         * @param amount amount of DarkenOutOfFocus
         */
        LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
        /**
         * Creates a pentagon bokeh effect
         */
        LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
            this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
        };
        /**
         * Disables the pentagon bokeh effect
         */
        LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
            this._highlightsPostProcess.updateEffect();
        };
        /**
         * Enables noise blur
         */
        LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
        /**
         * Disables noise blur
         */
        LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
        /**
         * Sets the HighlightsGain amount
         * @param amount amount of HighlightsGain
         */
        LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
            this._highlightsGain = amount;
        };
        /**
         * Sets the HighlightsThreshold amount
         * @param amount amount of HighlightsThreshold
         */
        LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
            if (this._highlightsGain === -1) {
                this._highlightsGain = 1.0;
            }
            this._highlightsThreshold = amount;
        };
        /**
         * Disables highlights
         */
        LensRenderingPipeline.prototype.disableHighlights = function () {
            this._highlightsGain = -1;
        };
        /**
         * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
         * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
         */
        LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
            if (disableDepthRender === void 0) { disableDepthRender = false; }
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
            this._chromaticAberrationPostProcess = null;
            this._highlightsPostProcess = null;
            this._depthOfFieldPostProcess = null;
            this._grainTexture.dispose();
            if (disableDepthRender) {
                this._scene.disableDepthRenderer();
            }
        };
        // colors shifting and distortion
        LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
            var _this = this;
            this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
            [], // samplers
            ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._chromaticAberrationPostProcess.onApply = function (effect) {
                effect.setFloat('chromatic_aberration', _this._chromaticAberration);
                effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
                effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
                effect.setFloat('radialIntensity', 1);
                effect.setFloat2('direction', 17, 17);
                effect.setFloat2('centerPosition', 0.5, 0.5);
            };
        };
        // highlights enhancing
        LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
            var _this = this;
            this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
            [], // samplers
            ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
            this._highlightsPostProcess.onApply = function (effect) {
                effect.setFloat('gain', _this._highlightsGain);
                effect.setFloat('threshold', _this._highlightsThreshold);
                effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
                effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
                effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
            };
        };
        // colors shifting and distortion
        LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
            var _this = this;
            this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
                "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
                "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
            ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
            this._depthOfFieldPostProcess.onApply = function (effect) {
                effect.setTexture("depthSampler", _this._depthTexture);
                effect.setTexture("grainSampler", _this._grainTexture);
                effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
                effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
                effect.setFloat('grain_amount', _this._grainAmount);
                effect.setBool('blur_noise', _this._blurNoise);
                effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
                effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
                effect.setFloat('distortion', _this._distortion);
                effect.setBool('dof_enabled', (_this._dofDistance !== -1));
                effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
                effect.setFloat('aperture', _this._dofAperture);
                effect.setFloat('darken', _this._dofDarken);
                effect.setFloat('edge_blur', _this._edgeBlur);
                effect.setBool('highlights', (_this._highlightsGain !== -1));
                if (_this._scene.activeCamera) {
                    effect.setFloat('near', _this._scene.activeCamera.minZ);
                    effect.setFloat('far', _this._scene.activeCamera.maxZ);
                }
            };
        };
        // creates a black and white random noise texture, 512x512
        LensRenderingPipeline.prototype._createGrainTexture = function () {
            var size = 512;
            this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
            this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
            var context = this._grainTexture.getContext();
            var rand = function (min, max) {
                return Math.random() * (max - min) + min;
            };
            var value;
            for (var x = 0; x < size; x++) {
                for (var y = 0; y < size; y++) {
                    value = Math.floor(rand(0.42, 0.58) * 255);
                    context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
                    context.fillRect(x, y, 1, 1);
                }
            }
            this._grainTexture.update(false);
        };
        return LensRenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.LensRenderingPipeline = LensRenderingPipeline;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.lensRenderingPipeline.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Standard rendering pipeline
     * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
     * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
     */
    var StandardRenderingPipeline = /** @class */ (function (_super) {
        __extends(StandardRenderingPipeline, _super);
        /**
         * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
         * @constructor
         * @param name The rendering pipeline name
         * @param scene The scene linked to this pipeline
         * @param ratio The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
         * @param cameras The array of cameras that the rendering pipeline will be attached to
         */
        function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
            if (originalPostProcess === void 0) { originalPostProcess = null; }
            var _this = _super.call(this, scene.getEngine(), name) || this;
            /**
             * Post-process used to down scale an image x4
             */
            _this.downSampleX4PostProcess = null;
            /**
             * Post-process used to calculate the illuminated surfaces controlled by a threshold
             */
            _this.brightPassPostProcess = null;
            /**
             * Post-process array storing all the horizontal blur post-processes used by the pipeline
             */
            _this.blurHPostProcesses = [];
            /**
             * Post-process array storing all the vertical blur post-processes used by the pipeline
             */
            _this.blurVPostProcesses = [];
            /**
             * Post-process used to add colors of 2 textures (typically brightness + real scene color)
             */
            _this.textureAdderPostProcess = null;
            /**
             * Post-process used to create volumetric lighting effect
             */
            _this.volumetricLightPostProcess = null;
            /**
             * Post-process used to smooth the previous volumetric light post-process on the X axis
             */
            _this.volumetricLightSmoothXPostProcess = null;
            /**
             * Post-process used to smooth the previous volumetric light post-process on the Y axis
             */
            _this.volumetricLightSmoothYPostProcess = null;
            /**
             * Post-process used to merge the volumetric light effect and the real scene color
             */
            _this.volumetricLightMergePostProces = null;
            /**
             * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
             */
            _this.volumetricLightFinalPostProcess = null;
            /**
             * Base post-process used to calculate the average luminance of the final image for HDR
             */
            _this.luminancePostProcess = null;
            /**
             * Post-processes used to create down sample post-processes in order to get
             * the average luminance of the final image for HDR
             * Array of length "StandardRenderingPipeline.LuminanceSteps"
             */
            _this.luminanceDownSamplePostProcesses = [];
            /**
             * Post-process used to create a HDR effect (light adaptation)
             */
            _this.hdrPostProcess = null;
            /**
             * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
             */
            _this.textureAdderFinalPostProcess = null;
            /**
             * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
             */
            _this.lensFlareFinalPostProcess = null;
            /**
             * Post-process used to merge the final HDR post-process and the real scene color
             */
            _this.hdrFinalPostProcess = null;
            /**
             * Post-process used to create a lens flare effect
             */
            _this.lensFlarePostProcess = null;
            /**
             * Post-process that merges the result of the lens flare post-process and the real scene color
             */
            _this.lensFlareComposePostProcess = null;
            /**
             * Post-process used to create a motion blur effect
             */
            _this.motionBlurPostProcess = null;
            /**
             * Post-process used to create a depth of field effect
             */
            _this.depthOfFieldPostProcess = null;
            /**
             * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
             */
            _this.fxaaPostProcess = null;
            // Values
            /**
             * Represents the brightness threshold in order to configure the illuminated surfaces
             */
            _this.brightThreshold = 1.0;
            /**
             * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
             */
            _this.blurWidth = 512.0;
            /**
             * Sets if the blur for highlighted surfaces must be only horizontal
             */
            _this.horizontalBlur = false;
            /**
             * Sets the overall exposure used by the pipeline
             */
            _this.exposure = 1.0;
            /**
             * Texture used typically to simulate "dirty" on camera lens
             */
            _this.lensTexture = null;
            /**
             * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
             */
            _this.volumetricLightCoefficient = 0.2;
            /**
             * The overall power of volumetric lights, typically in interval [0, 10] maximum
             */
            _this.volumetricLightPower = 4.0;
            /**
             * Used the set the blur intensity to smooth the volumetric lights
             */
            _this.volumetricLightBlurScale = 64.0;
            /**
             * Light (spot or directional) used to generate the volumetric lights rays
             * The source light must have a shadow generate so the pipeline can get its
             * depth map
             */
            _this.sourceLight = null;
            /**
             * For eye adaptation, represents the minimum luminance the eye can see
             */
            _this.hdrMinimumLuminance = 1.0;
            /**
             * For eye adaptation, represents the decrease luminance speed
             */
            _this.hdrDecreaseRate = 0.5;
            /**
             * For eye adaptation, represents the increase luminance speed
             */
            _this.hdrIncreaseRate = 0.5;
            /**
             * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
             */
            _this.lensColorTexture = null;
            /**
             * The overall strengh for the lens flare effect
             */
            _this.lensFlareStrength = 20.0;
            /**
             * Dispersion coefficient for lens flare ghosts
             */
            _this.lensFlareGhostDispersal = 1.4;
            /**
             * Main lens flare halo width
             */
            _this.lensFlareHaloWidth = 0.7;
            /**
             * Based on the lens distortion effect, defines how much the lens flare result
             * is distorted
             */
            _this.lensFlareDistortionStrength = 16.0;
            /**
             * Lens star texture must be used to simulate rays on the flares and is available
             * in the documentation
             */
            _this.lensStarTexture = null;
            /**
             * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
             * flare effect by taking account of the dirt texture
             */
            _this.lensFlareDirtTexture = null;
            /**
             * Represents the focal length for the depth of field effect
             */
            _this.depthOfFieldDistance = 10.0;
            /**
             * Represents the blur intensity for the blurred part of the depth of field effect
             */
            _this.depthOfFieldBlurWidth = 64.0;
            /**
             * For motion blur, defines how much the image is blurred by the movement
             */
            _this.motionStrength = 1.0;
            /**
             * List of animations for the pipeline (IAnimatable implementation)
             */
            _this.animations = [];
            _this._currentDepthOfFieldSource = null;
            _this._hdrCurrentLuminance = 1.0;
            // Getters and setters
            _this._bloomEnabled = false;
            _this._depthOfFieldEnabled = false;
            _this._vlsEnabled = false;
            _this._lensFlareEnabled = false;
            _this._hdrEnabled = false;
            _this._motionBlurEnabled = false;
            _this._fxaaEnabled = false;
            _this._motionBlurSamples = 64.0;
            _this._volumetricLightStepsCount = 50.0;
            _this._samples = 1;
            _this._cameras = cameras || [];
            // Initialize
            _this._scene = scene;
            _this._basePostProcess = originalPostProcess;
            _this._ratio = ratio;
            // Misc
            _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
            // Finish
            scene.postProcessRenderPipelineManager.addPipeline(_this);
            _this._buildPipeline();
            return _this;
        }
        Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
            /**
             * @ignore
             * Specifies if the bloom pipeline is enabled
             */
            get: function () {
                return this._bloomEnabled;
            },
            set: function (enabled) {
                if (this._bloomEnabled === enabled) {
                    return;
                }
                this._bloomEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
            /**
             * @ignore
             * Specifies if the depth of field pipeline is enabed
             */
            get: function () {
                return this._depthOfFieldEnabled;
            },
            set: function (enabled) {
                if (this._depthOfFieldEnabled === enabled) {
                    return;
                }
                this._depthOfFieldEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
            /**
             * @ignore
             * Specifies if the lens flare pipeline is enabed
             */
            get: function () {
                return this._lensFlareEnabled;
            },
            set: function (enabled) {
                if (this._lensFlareEnabled === enabled) {
                    return;
                }
                this._lensFlareEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
            /**
             * @ignore
             * Specifies if the HDR pipeline is enabled
             */
            get: function () {
                return this._hdrEnabled;
            },
            set: function (enabled) {
                if (this._hdrEnabled === enabled) {
                    return;
                }
                this._hdrEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
            /**
             * @ignore
             * Specifies if the volumetric lights scattering effect is enabled
             */
            get: function () {
                return this._vlsEnabled;
            },
            set: function (enabled) {
                if (this._vlsEnabled === enabled) {
                    return;
                }
                if (enabled) {
                    var geometry = this._scene.enableGeometryBufferRenderer();
                    if (!geometry) {
                        BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
                        return;
                    }
                }
                this._vlsEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
            /**
             * @ignore
             * Specifies if the motion blur effect is enabled
             */
            get: function () {
                return this._motionBlurEnabled;
            },
            set: function (enabled) {
                if (this._motionBlurEnabled === enabled) {
                    return;
                }
                this._motionBlurEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
            /**
             * Specifies if anti-aliasing is enabled
             */
            get: function () {
                return this._fxaaEnabled;
            },
            set: function (enabled) {
                if (this._fxaaEnabled === enabled) {
                    return;
                }
                this._fxaaEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
            /**
             * Specifies the number of steps used to calculate the volumetric lights
             * Typically in interval [50, 200]
             */
            get: function () {
                return this._volumetricLightStepsCount;
            },
            set: function (count) {
                if (this.volumetricLightPostProcess) {
                    this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
                }
                this._volumetricLightStepsCount = count;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
            /**
             * Specifies the number of samples used for the motion blur effect
             * Typically in interval [16, 64]
             */
            get: function () {
                return this._motionBlurSamples;
            },
            set: function (samples) {
                if (this.motionBlurPostProcess) {
                    this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
                }
                this._motionBlurSamples = samples;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
            /**
             * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
             */
            get: function () {
                return this._samples;
            },
            set: function (sampleCount) {
                if (this._samples === sampleCount) {
                    return;
                }
                this._samples = sampleCount;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        StandardRenderingPipeline.prototype._buildPipeline = function () {
            var _this = this;
            var ratio = this._ratio;
            var scene = this._scene;
            this._disposePostProcesses();
            this._reset();
            // Create pass post-process
            if (!this._basePostProcess) {
                this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
                this.originalPostProcess.onApply = function (effect) {
                    _this._currentDepthOfFieldSource = _this.originalPostProcess;
                };
            }
            else {
                this.originalPostProcess = this._basePostProcess;
            }
            if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
                this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
            }
            this._currentDepthOfFieldSource = this.originalPostProcess;
            if (this._bloomEnabled) {
                // Create down sample X4 post-process
                this._createDownSampleX4PostProcess(scene, ratio / 2);
                // Create bright pass post-process
                this._createBrightPassPostProcess(scene, ratio / 2);
                // Create gaussian blur post-processes (down sampling blurs)
                this._createBlurPostProcesses(scene, ratio / 4, 1);
                // Create texture adder post-process
                this._createTextureAdderPostProcess(scene, ratio);
                // Create depth-of-field source post-process
                this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
                this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
            }
            if (this._vlsEnabled) {
                // Create volumetric light
                this._createVolumetricLightPostProcess(scene, ratio);
                // Create volumetric light final post-process
                this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
                this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
            }
            if (this._lensFlareEnabled) {
                // Create lens flare post-process
                this._createLensFlarePostProcess(scene, ratio);
                // Create depth-of-field source post-process post lens-flare and disable it now
                this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
                this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
            }
            if (this._hdrEnabled) {
                // Create luminance
                this._createLuminancePostProcesses(scene, this._floatTextureType);
                // Create HDR
                this._createHdrPostProcess(scene, ratio);
                // Create depth-of-field source post-process post hdr and disable it now
                this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
                this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
            }
            if (this._depthOfFieldEnabled) {
                // Create gaussian blur used by depth-of-field
                this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
                // Create depth-of-field post-process
                this._createDepthOfFieldPostProcess(scene, ratio);
            }
            if (this._motionBlurEnabled) {
                // Create motion blur post-process
                this._createMotionBlurPostProcess(scene, ratio);
            }
            if (this._fxaaEnabled) {
                // Create fxaa post-process
                this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
                this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
            }
            if (this._cameras !== null) {
                this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
            }
            if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
                BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
            }
        };
        // Down Sample X4 Post-Processs
        StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
            var _this = this;
            var downSampleX4Offsets = new Array(32);
            this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.downSampleX4PostProcess.onApply = function (effect) {
                var id = 0;
                var width = _this.downSampleX4PostProcess.width;
                var height = _this.downSampleX4PostProcess.height;
                for (var i = -2; i < 2; i++) {
                    for (var j = -2; j < 2; j++) {
                        downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
                        downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
                        id += 2;
                    }
                }
                effect.setArray2("dsOffsets", downSampleX4Offsets);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
        };
        // Brightpass Post-Process
        StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
            var _this = this;
            var brightOffsets = new Array(8);
            this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.brightPassPostProcess.onApply = function (effect) {
                var sU = (1.0 / _this.brightPassPostProcess.width);
                var sV = (1.0 / _this.brightPassPostProcess.height);
                brightOffsets[0] = -0.5 * sU;
                brightOffsets[1] = 0.5 * sV;
                brightOffsets[2] = 0.5 * sU;
                brightOffsets[3] = 0.5 * sV;
                brightOffsets[4] = -0.5 * sU;
                brightOffsets[5] = -0.5 * sV;
                brightOffsets[6] = 0.5 * sU;
                brightOffsets[7] = -0.5 * sV;
                effect.setArray2("dsOffsets", brightOffsets);
                effect.setFloat("brightThreshold", _this.brightThreshold);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
        };
        // Create blur H&V post-processes
        StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
            var _this = this;
            if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
            var engine = scene.getEngine();
            var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            blurX.onActivateObservable.add(function () {
                var dw = blurX.width / engine.getRenderWidth();
                blurX.kernel = _this[blurWidthKey] * dw;
            });
            blurY.onActivateObservable.add(function () {
                var dw = blurY.height / engine.getRenderHeight();
                blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
            });
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
            this.blurHPostProcesses.push(blurX);
            this.blurVPostProcesses.push(blurY);
        };
        // Create texture adder post-process
        StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
            var _this = this;
            this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.textureAdderPostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
                effect.setTexture("lensSampler", _this.lensTexture);
                effect.setFloat("exposure", _this.exposure);
                _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
        };
        StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
            var _this = this;
            var geometryRenderer = scene.enableGeometryBufferRenderer();
            geometryRenderer.enablePosition = true;
            var geometry = geometryRenderer.getGBuffer();
            // Base post-process
            this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
            var depthValues = BABYLON.Vector2.Zero();
            this.volumetricLightPostProcess.onApply = function (effect) {
                if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
                    var generator = _this.sourceLight.getShadowGenerator();
                    effect.setTexture("shadowMapSampler", generator.getShadowMap());
                    effect.setTexture("positionSampler", geometry.textures[2]);
                    effect.setColor3("sunColor", _this.sourceLight.diffuse);
                    effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
                    effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
                    effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
                    effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
                    effect.setFloat("scatteringPower", _this.volumetricLightPower);
                    depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
                    depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
                    effect.setVector2("depthValues", depthValues);
                }
            };
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
            // Smooth
            this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
            // Merge
            this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
            this.volumetricLightMergePostProces.onApply = function (effect) {
                effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
                _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
            };
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
        };
        // Create luminance
        StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
            var _this = this;
            // Create luminance
            var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
            this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
            var offsets = [];
            this.luminancePostProcess.onApply = function (effect) {
                var sU = (1.0 / _this.luminancePostProcess.width);
                var sV = (1.0 / _this.luminancePostProcess.height);
                offsets[0] = -0.5 * sU;
                offsets[1] = 0.5 * sV;
                offsets[2] = 0.5 * sU;
                offsets[3] = 0.5 * sV;
                offsets[4] = -0.5 * sU;
                offsets[5] = -0.5 * sV;
                offsets[6] = 0.5 * sU;
                offsets[7] = -0.5 * sV;
                effect.setArray2("lumOffsets", offsets);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
            // Create down sample luminance
            for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
                var size = Math.pow(3, i);
                var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
                if (i === 0) {
                    defines += "#define FINAL_DOWN_SAMPLER";
                }
                var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
                this.luminanceDownSamplePostProcesses.push(postProcess);
            }
            // Create callbacks and add effects
            var lastLuminance = this.luminancePostProcess;
            this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
                var downSampleOffsets = new Array(18);
                pp.onApply = function (effect) {
                    if (!lastLuminance) {
                        return;
                    }
                    var id = 0;
                    for (var x = -1; x < 2; x++) {
                        for (var y = -1; y < 2; y++) {
                            downSampleOffsets[id] = x / lastLuminance.width;
                            downSampleOffsets[id + 1] = y / lastLuminance.height;
                            id += 2;
                        }
                    }
                    effect.setArray2("dsOffsets", downSampleOffsets);
                    effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
                    if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
                        lastLuminance = _this.luminancePostProcess;
                    }
                    else {
                        lastLuminance = pp;
                    }
                };
                if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
                    pp.onAfterRender = function (effect) {
                        var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
                        var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
                        _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
                    };
                }
                _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
            });
        };
        // Create HDR post-process
        StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
            var _this = this;
            this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            var outputLiminance = 1;
            var time = 0;
            var lastTime = 0;
            this.hdrPostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
                time += scene.getEngine().getDeltaTime();
                if (outputLiminance < 0) {
                    outputLiminance = _this._hdrCurrentLuminance;
                }
                else {
                    var dt = (lastTime - time) / 1000.0;
                    if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
                        outputLiminance += _this.hdrDecreaseRate * dt;
                    }
                    else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
                        outputLiminance -= _this.hdrIncreaseRate * dt;
                    }
                    else {
                        outputLiminance = _this._hdrCurrentLuminance;
                    }
                }
                outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
                effect.setFloat("averageLuminance", outputLiminance);
                lastTime = time;
                _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
            };
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
        };
        // Create lens flare post-process
        StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
            var _this = this;
            this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
            this._createBlurPostProcesses(scene, ratio / 4, 2);
            this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
            var resolution = new BABYLON.Vector2(0, 0);
            // Lens flare
            this.lensFlarePostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
                effect.setTexture("lensColorSampler", _this.lensColorTexture);
                effect.setFloat("strength", _this.lensFlareStrength);
                effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
                effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
                // Shift
                resolution.x = _this.lensFlarePostProcess.width;
                resolution.y = _this.lensFlarePostProcess.height;
                effect.setVector2("resolution", resolution);
                effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
            };
            // Compose
            var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
            var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
            this.lensFlareComposePostProcess.onApply = function (effect) {
                if (!_this._scene.activeCamera) {
                    return;
                }
                effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
                effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
                effect.setTexture("lensStarSampler", _this.lensStarTexture);
                // Lens start rotation matrix
                var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
                var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
                var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
                camRot *= 4.0;
                var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
                var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
                effect.setMatrix("lensStarMatrix", lensStarMatrix);
                _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
            };
        };
        // Create depth-of-field post-process
        StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
            var _this = this;
            this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this.depthOfFieldPostProcess.onApply = function (effect) {
                effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
                effect.setTexture("depthSampler", _this._getDepthTexture());
                effect.setFloat("distance", _this.depthOfFieldDistance);
            };
            // Add to pipeline
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
        };
        // Create motion blur post-process
        StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
            var _this = this;
            this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            var motionScale = 0;
            var prevViewProjection = BABYLON.Matrix.Identity();
            var invViewProjection = BABYLON.Matrix.Identity();
            var viewProjection = BABYLON.Matrix.Identity();
            var screenSize = BABYLON.Vector2.Zero();
            this.motionBlurPostProcess.onApply = function (effect) {
                viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
                viewProjection.invertToRef(invViewProjection);
                effect.setMatrix("inverseViewProjection", invViewProjection);
                effect.setMatrix("prevViewProjection", prevViewProjection);
                prevViewProjection = viewProjection;
                screenSize.x = _this.motionBlurPostProcess.width;
                screenSize.y = _this.motionBlurPostProcess.height;
                effect.setVector2("screenSize", screenSize);
                motionScale = scene.getEngine().getFps() / 60.0;
                effect.setFloat("motionScale", motionScale);
                effect.setFloat("motionStrength", _this.motionStrength);
                effect.setTexture("depthSampler", _this._getDepthTexture());
            };
            this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
        };
        StandardRenderingPipeline.prototype._getDepthTexture = function () {
            if (this._scene.getEngine().getCaps().drawBuffersExtension) {
                var renderer = this._scene.enableGeometryBufferRenderer();
                return renderer.getGBuffer().textures[0];
            }
            return this._scene.enableDepthRenderer().getDepthMap();
        };
        StandardRenderingPipeline.prototype._disposePostProcesses = function () {
            for (var i = 0; i < this._cameras.length; i++) {
                var camera = this._cameras[i];
                if (this.originalPostProcess) {
                    this.originalPostProcess.dispose(camera);
                }
                if (this.downSampleX4PostProcess) {
                    this.downSampleX4PostProcess.dispose(camera);
                }
                if (this.brightPassPostProcess) {
                    this.brightPassPostProcess.dispose(camera);
                }
                if (this.textureAdderPostProcess) {
                    this.textureAdderPostProcess.dispose(camera);
                }
                if (this.textureAdderFinalPostProcess) {
                    this.textureAdderFinalPostProcess.dispose(camera);
                }
                if (this.volumetricLightPostProcess) {
                    this.volumetricLightPostProcess.dispose(camera);
                }
                if (this.volumetricLightSmoothXPostProcess) {
                    this.volumetricLightSmoothXPostProcess.dispose(camera);
                }
                if (this.volumetricLightSmoothYPostProcess) {
                    this.volumetricLightSmoothYPostProcess.dispose(camera);
                }
                if (this.volumetricLightMergePostProces) {
                    this.volumetricLightMergePostProces.dispose(camera);
                }
                if (this.volumetricLightFinalPostProcess) {
                    this.volumetricLightFinalPostProcess.dispose(camera);
                }
                if (this.lensFlarePostProcess) {
                    this.lensFlarePostProcess.dispose(camera);
                }
                if (this.lensFlareComposePostProcess) {
                    this.lensFlareComposePostProcess.dispose(camera);
                }
                for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
                    this.luminanceDownSamplePostProcesses[j].dispose(camera);
                }
                if (this.luminancePostProcess) {
                    this.luminancePostProcess.dispose(camera);
                }
                if (this.hdrPostProcess) {
                    this.hdrPostProcess.dispose(camera);
                }
                if (this.hdrFinalPostProcess) {
                    this.hdrFinalPostProcess.dispose(camera);
                }
                if (this.depthOfFieldPostProcess) {
                    this.depthOfFieldPostProcess.dispose(camera);
                }
                if (this.motionBlurPostProcess) {
                    this.motionBlurPostProcess.dispose(camera);
                }
                if (this.fxaaPostProcess) {
                    this.fxaaPostProcess.dispose(camera);
                }
                for (var j = 0; j < this.blurHPostProcesses.length; j++) {
                    this.blurHPostProcesses[j].dispose(camera);
                }
                for (var j = 0; j < this.blurVPostProcesses.length; j++) {
                    this.blurVPostProcesses[j].dispose(camera);
                }
            }
            this.originalPostProcess = null;
            this.downSampleX4PostProcess = null;
            this.brightPassPostProcess = null;
            this.textureAdderPostProcess = null;
            this.textureAdderFinalPostProcess = null;
            this.volumetricLightPostProcess = null;
            this.volumetricLightSmoothXPostProcess = null;
            this.volumetricLightSmoothYPostProcess = null;
            this.volumetricLightMergePostProces = null;
            this.volumetricLightFinalPostProcess = null;
            this.lensFlarePostProcess = null;
            this.lensFlareComposePostProcess = null;
            this.luminancePostProcess = null;
            this.hdrPostProcess = null;
            this.hdrFinalPostProcess = null;
            this.depthOfFieldPostProcess = null;
            this.motionBlurPostProcess = null;
            this.fxaaPostProcess = null;
            this.luminanceDownSamplePostProcesses = [];
            this.blurHPostProcesses = [];
            this.blurVPostProcesses = [];
        };
        /**
         * Dispose of the pipeline and stop all post processes
         */
        StandardRenderingPipeline.prototype.dispose = function () {
            this._disposePostProcesses();
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
            _super.prototype.dispose.call(this);
        };
        /**
         * Serialize the rendering pipeline (Used when exporting)
         * @returns the serialized object
         */
        StandardRenderingPipeline.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            if (this.sourceLight) {
                serializationObject.sourceLightId = this.sourceLight.id;
            }
            serializationObject.customType = "StandardRenderingPipeline";
            return serializationObject;
        };
        /**
         * Parse the serialized pipeline
         * @param source Source pipeline.
         * @param scene The scene to load the pipeline to.
         * @param rootUrl The URL of the serialized pipeline.
         * @returns An instantiated pipeline from the serialized object.
         */
        StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
            var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
            if (source.sourceLightId) {
                p.sourceLight = scene.getLightByID(source.sourceLightId);
            }
            return p;
        };
        /**
         * Luminance steps
         */
        StandardRenderingPipeline.LuminanceSteps = 6;
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "exposure", void 0);
        __decorate([
            BABYLON.serializeAsTexture("lensTexture")
        ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
        __decorate([
            BABYLON.serializeAsTexture("lensColorTexture")
        ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
        __decorate([
            BABYLON.serializeAsTexture("lensStarTexture")
        ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
        __decorate([
            BABYLON.serializeAsTexture("lensFlareDirtTexture")
        ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "_ratio", void 0);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "HDREnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
        __decorate([
            BABYLON.serialize()
        ], StandardRenderingPipeline.prototype, "samples", null);
        return StandardRenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.standardRenderingPipeline.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Fxaa post process
     * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
     */
    var FxaaPostProcess = /** @class */ (function (_super) {
        __extends(FxaaPostProcess, _super);
        function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
            if (camera === void 0) { camera = null; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
            var defines = _this._getDefines();
            _this.updateEffect(defines);
            _this.onApplyObservable.add(function (effect) {
                var texelSize = _this.texelSize;
                effect.setFloat2("texelSize", texelSize.x, texelSize.y);
            });
            return _this;
        }
        FxaaPostProcess.prototype._getDefines = function () {
            var engine = this.getEngine();
            if (!engine) {
                return null;
            }
            var glInfo = engine.getGlInfo();
            if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
                return "#define MALI 1\n";
            }
            return null;
        };
        return FxaaPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.FxaaPostProcess = FxaaPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.fxaaPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
     */
    var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
        __extends(ChromaticAberrationPostProcess, _super);
        /**
         * Creates a new instance ChromaticAberrationPostProcess
         * @param name The name of the effect.
         * @param screenWidth The width of the screen to apply the effect on.
         * @param screenHeight The height of the screen to apply the effect on.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
            /**
             * The amount of seperation of rgb channels (default: 30)
             */
            _this.aberrationAmount = 30;
            /**
             * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
             */
            _this.radialIntensity = 0;
            /**
             * The normilized direction in which the rgb channels should be seperated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707))
             */
            _this.direction = new BABYLON.Vector2(0.707, 0.707);
            /**
             * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corder] (default: Vector2(0.5 ,0.5))
             */
            _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
            _this.onApplyObservable.add(function (effect) {
                effect.setFloat('chromatic_aberration', _this.aberrationAmount);
                effect.setFloat('screen_width', screenWidth);
                effect.setFloat('screen_height', screenHeight);
                effect.setFloat('radialIntensity', _this.radialIntensity);
                effect.setFloat2('direction', _this.direction.x, _this.direction.y);
                effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
            });
            return _this;
        }
        return ChromaticAberrationPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The GrainPostProcess adds noise to the image at mid luminance levels
     */
    var GrainPostProcess = /** @class */ (function (_super) {
        __extends(GrainPostProcess, _super);
        /**
         * Creates a new instance of @see GrainPostProcess
         * @param name The name of the effect.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
            /**
             * The intensity of the grain added (default: 30)
             */
            _this.intensity = 30;
            /**
             * If the grain should be randomized on every frame
             */
            _this.animated = false;
            _this.onApplyObservable.add(function (effect) {
                effect.setFloat('intensity', _this.intensity);
                effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
            });
            return _this;
        }
        return GrainPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.GrainPostProcess = GrainPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.grainPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The SharpenPostProcess applies a sharpen kernel to every pixel
     * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
     */
    var SharpenPostProcess = /** @class */ (function (_super) {
        __extends(SharpenPostProcess, _super);
        /**
         * Creates a new instance ConvolutionPostProcess
         * @param name The name of the effect.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
            /**
             * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
             */
            _this.colorAmount = 1.0;
            /**
             * How much sharpness should be applied (default: 0.3)
             */
            _this.edgeAmount = 0.3;
            _this.onApply = function (effect) {
                effect.setFloat2("screenSize", _this.width, _this.height);
                effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
            };
            return _this;
        }
        return SharpenPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.SharpenPostProcess = SharpenPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sharpenPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The Blur Post Process which blurs an image based on a kernel and direction.
     * Can be used twice in x and y directions to perform a guassian blur in two passes.
     */
    var BlurPostProcess = /** @class */ (function (_super) {
        __extends(BlurPostProcess, _super);
        /**
         * Creates a new instance BlurPostProcess
         * @param name The name of the effect.
         * @param direction The direction in which to blur the image.
         * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it.
         * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function BlurPostProcess(name, 
        /** The direction in which to blur the image. */
        direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (defines === void 0) { defines = ""; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "kernelBlur", ["delta", "direction", "cameraMinMaxZ"], ["circleOfConfusionSampler"], options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
            _this.direction = direction;
            _this.blockCompilation = blockCompilation;
            _this._packedFloat = false;
            _this._staticDefines = "";
            _this._staticDefines = defines;
            _this.onApplyObservable.add(function (effect) {
                if (_this._outputTexture) {
                    effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
                }
                else {
                    effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
                }
            });
            _this.kernel = kernel;
            return _this;
        }
        Object.defineProperty(BlurPostProcess.prototype, "kernel", {
            /**
             * Gets the length in pixels of the blur sample region
             */
            get: function () {
                return this._idealKernel;
            },
            /**
             * Sets the length in pixels of the blur sample region
             */
            set: function (v) {
                if (this._idealKernel === v) {
                    return;
                }
                v = Math.max(v, 1);
                this._idealKernel = v;
                this._kernel = this._nearestBestKernel(v);
                if (!this.blockCompilation) {
                    this._updateParameters();
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
            /**
             * Gets wether or not the blur is unpacking/repacking floats
             */
            get: function () {
                return this._packedFloat;
            },
            /**
             * Sets wether or not the blur needs to unpack/repack floats
             */
            set: function (v) {
                if (this._packedFloat === v) {
                    return;
                }
                this._packedFloat = v;
                if (!this.blockCompilation) {
                    this._updateParameters();
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Updates the effect with the current post process compile time values and recompiles the shader.
         * @param defines Define statements that should be added at the beginning of the shader. (default: null)
         * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
         * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
         * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
         * @param onCompiled Called when the shader has been compiled.
         * @param onError Called if there is an error when compiling a shader.
         */
        BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
            if (defines === void 0) { defines = null; }
            if (uniforms === void 0) { uniforms = null; }
            if (samplers === void 0) { samplers = null; }
            this._updateParameters(onCompiled, onError);
        };
        BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
            // Generate sampling offsets and weights
            var N = this._kernel;
            var centerIndex = (N - 1) / 2;
            // Generate Gaussian sampling weights over kernel
            var offsets = [];
            var weights = [];
            var totalWeight = 0;
            for (var i = 0; i < N; i++) {
                var u = i / (N - 1);
                var w = this._gaussianWeight(u * 2.0 - 1);
                offsets[i] = (i - centerIndex);
                weights[i] = w;
                totalWeight += w;
            }
            // Normalize weights
            for (var i = 0; i < weights.length; i++) {
                weights[i] /= totalWeight;
            }
            // Optimize: combine samples to take advantage of hardware linear sampling
            // Walk from left to center, combining pairs (symmetrically)
            var linearSamplingWeights = [];
            var linearSamplingOffsets = [];
            var linearSamplingMap = [];
            for (var i = 0; i <= centerIndex; i += 2) {
                var j = Math.min(i + 1, Math.floor(centerIndex));
                var singleCenterSample = i === j;
                if (singleCenterSample) {
                    linearSamplingMap.push({ o: offsets[i], w: weights[i] });
                }
                else {
                    var sharedCell = j === centerIndex;
                    var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
                    var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
                    if (offsetLinear === 0) {
                        linearSamplingMap.push({ o: offsets[i], w: weights[i] });
                        linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
                    }
                    else {
                        linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
                        linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
                    }
                }
            }
            for (var i = 0; i < linearSamplingMap.length; i++) {
                linearSamplingOffsets[i] = linearSamplingMap[i].o;
                linearSamplingWeights[i] = linearSamplingMap[i].w;
            }
            // Replace with optimized
            offsets = linearSamplingOffsets;
            weights = linearSamplingWeights;
            // Generate shaders
            var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
            var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
            var varyingCount = Math.min(offsets.length, freeVaryingVec2);
            var defines = "";
            defines += this._staticDefines;
            // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
            if (this._staticDefines.indexOf("DOF") != -1) {
                defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
                varyingCount--;
            }
            for (var i = 0; i < varyingCount; i++) {
                defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
                defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
            }
            var depCount = 0;
            for (var i = freeVaryingVec2; i < offsets.length; i++) {
                defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
                defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
                depCount++;
            }
            if (this.packedFloat) {
                defines += "#define PACKEDFLOAT 1";
            }
            this.blockCompilation = false;
            _super.prototype.updateEffect.call(this, defines, null, null, {
                varyingCount: varyingCount,
                depCount: depCount
            }, onCompiled, onError);
        };
        /**
         * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
         * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
         * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
         * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
         * The gaps between physical kernels are compensated for in the weighting of the samples
         * @param idealKernel Ideal blur kernel.
         * @return Nearest best kernel.
         */
        BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
            var v = Math.round(idealKernel);
            for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
                var k = _a[_i];
                if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
                    return Math.max(k, 3);
                }
            }
            return Math.max(v, 3);
        };
        /**
         * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
         * @param x The point on the Gaussian distribution to sample.
         * @return the value of the Gaussian function at x.
         */
        BlurPostProcess.prototype._gaussianWeight = function (x) {
            //reference: Engine/ImageProcessingBlur.cpp #dcc760
            // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
            // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
            // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
            // truncated at around 1.3% of peak strength.
            //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
            var sigma = (1 / 3);
            var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
            var exponent = -((x * x) / (2.0 * sigma * sigma));
            var weight = (1.0 / denominator) * Math.exp(exponent);
            return weight;
        };
        /**
          * Generates a string that can be used as a floating point number in GLSL.
          * @param x Value to print.
          * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
          * @return GLSL float string.
          */
        BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
            if (decimalFigures === void 0) { decimalFigures = 8; }
            return x.toFixed(decimalFigures).replace(/0+$/, '');
        };
        return BlurPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.BlurPostProcess = BlurPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.blurPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
     * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
     * based on samples that have a large difference in distance than the center pixel.
     * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
     */
    var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
        __extends(DepthOfFieldBlurPostProcess, _super);
        /**
         * Creates a new instance CircleOfConfusionPostProcess
         * @param name The name of the effect.
         * @param scene The scene the effect belongs to.
         * @param direction The direction the blur should be applied.
         * @param kernel The size of the kernel used to blur.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
         * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (imageToBlur === void 0) { imageToBlur = null; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, direction, kernel, options, camera, samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, "#define DOF 1\r\n", blockCompilation) || this;
            _this.direction = direction;
            _this.onApplyObservable.add(function (effect) {
                if (imageToBlur != null) {
                    effect.setTextureFromPostProcess("textureSampler", imageToBlur);
                }
                effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
                if (scene.activeCamera) {
                    effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
                }
            });
            return _this;
        }
        return DepthOfFieldBlurPostProcess;
    }(BABYLON.BlurPostProcess));
    BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Options to be set when merging outputs from the default pipeline.
     */
    var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
        function DepthOfFieldMergePostProcessOptions() {
        }
        return DepthOfFieldMergePostProcessOptions;
    }());
    BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
    /**
     * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
     */
    var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
        __extends(DepthOfFieldMergePostProcess, _super);
        /**
         * Creates a new instance of DepthOfFieldMergePostProcess
         * @param name The name of the effect.
         * @param originalFromInput Post process which's input will be used for the merge.
         * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
         * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
            _this.blurSteps = blurSteps;
            _this.onApplyObservable.add(function (effect) {
                effect.setTextureFromPostProcess("textureSampler", originalFromInput);
                effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
                blurSteps.forEach(function (step, index) {
                    effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
                });
            });
            if (!blockCompilation) {
                _this.updateEffect();
            }
            return _this;
        }
        /**
         * Updates the effect with the current post process compile time values and recompiles the shader.
         * @param defines Define statements that should be added at the beginning of the shader. (default: null)
         * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
         * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
         * @param indexParameters The index parameters to be used for babylons include syntax "#include<kernelBlurVaryingDeclaration>[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx
         * @param onCompiled Called when the shader has been compiled.
         * @param onError Called if there is an error when compiling a shader.
         */
        DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
            if (defines === void 0) { defines = null; }
            if (uniforms === void 0) { uniforms = null; }
            if (samplers === void 0) { samplers = null; }
            if (!defines) {
                defines = "";
                defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
            }
            _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
        };
        return DepthOfFieldMergePostProcess;
    }(BABYLON.PostProcess));
    BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
     */
    var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
        __extends(CircleOfConfusionPostProcess, _super);
        /**
         * Creates a new instance CircleOfConfusionPostProcess
         * @param name The name of the effect.
         * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
            /**
             * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
             */
            _this.lensSize = 50;
            /**
             * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
             */
            _this.fStop = 1.4;
            /**
             * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
             */
            _this.focusDistance = 2000;
            /**
             * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
             */
            _this.focalLength = 50;
            _this._depthTexture = null;
            _this._depthTexture = depthTexture;
            _this.onApplyObservable.add(function (effect) {
                if (!_this._depthTexture) {
                    BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
                    return;
                }
                effect.setTexture("depthSampler", _this._depthTexture);
                // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
                var aperture = _this.lensSize / _this.fStop;
                var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
                effect.setFloat('focusDistance', _this.focusDistance);
                effect.setFloat('cocPrecalculation', cocPrecalculation);
                effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
            });
            return _this;
        }
        Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
            /**
             * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
             */
            set: function (value) {
                this._depthTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        return CircleOfConfusionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Specifies the level of max blur that should be applied when using the depth of field effect
     */
    var DepthOfFieldEffectBlurLevel;
    (function (DepthOfFieldEffectBlurLevel) {
        /**
         * Subtle blur
         */
        DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
        /**
         * Medium blur
         */
        DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
        /**
         * Large blur
         */
        DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
    })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
    /**
     * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
     */
    var DepthOfFieldEffect = /** @class */ (function (_super) {
        __extends(DepthOfFieldEffect, _super);
        /**
         * Creates a new instance DepthOfFieldEffect
         * @param scene The scene the effect belongs to.
         * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed.
         * @param pipelineTextureType The type of texture to be used when performing the post processing.
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
            if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
            if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
                return _this._effects;
            }, true) || this;
            /**
             * @hidden Internal post processes in depth of field effect
             */
            _this._effects = [];
            // Circle of confusion value for each pixel is used to determine how much to blur that pixel
            _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
            // Create a pyramid of blurred images (eg. fullSize 1/4 blur, half size 1/2 blur, quarter size 3/4 blur, eith size 4/4 blur)
            // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
            // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
            _this._depthOfFieldBlurY = [];
            _this._depthOfFieldBlurX = [];
            var blurCount = 1;
            var kernelSize = 15;
            switch (blurLevel) {
                case DepthOfFieldEffectBlurLevel.High: {
                    blurCount = 3;
                    kernelSize = 51;
                    break;
                }
                case DepthOfFieldEffectBlurLevel.Medium: {
                    blurCount = 2;
                    kernelSize = 31;
                    break;
                }
                default: {
                    kernelSize = 15;
                    blurCount = 1;
                    break;
                }
            }
            var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
            var ratio = 1.0;
            for (var i = 0; i < blurCount; i++) {
                var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
                blurY.autoClear = false;
                ratio = 0.75 / Math.pow(2, i);
                var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, ratio, null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
                blurX.autoClear = false;
                _this._depthOfFieldBlurY.push(blurY);
                _this._depthOfFieldBlurX.push(blurX);
            }
            // Set all post processes on the effect.
            _this._effects = [_this._circleOfConfusion];
            for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
                _this._effects.push(_this._depthOfFieldBlurY[i]);
                _this._effects.push(_this._depthOfFieldBlurX[i]);
            }
            // Merge blurred images with original image based on circleOfConfusion
            _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
            _this._dofMerge.autoClear = false;
            _this._effects.push(_this._dofMerge);
            return _this;
        }
        Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
            get: function () {
                return this._circleOfConfusion.focalLength;
            },
            /**
             * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
             */
            set: function (value) {
                this._circleOfConfusion.focalLength = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
            get: function () {
                return this._circleOfConfusion.fStop;
            },
            /**
             * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
             */
            set: function (value) {
                this._circleOfConfusion.fStop = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
            get: function () {
                return this._circleOfConfusion.focusDistance;
            },
            /**
             * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
             */
            set: function (value) {
                this._circleOfConfusion.focusDistance = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
            get: function () {
                return this._circleOfConfusion.lensSize;
            },
            /**
             * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diamater of the resulting aperture can be computed by lensSize/fStop.
             */
            set: function (value) {
                this._circleOfConfusion.lensSize = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
            /**
             * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function.
             */
            set: function (value) {
                this._circleOfConfusion.depthTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes each of the internal effects for a given camera.
         * @param camera The camera to dispose the effect on.
         */
        DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
            for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
                this._effects[effectIndex].dispose(camera);
            }
        };
        /**
         * @hidden Internal
         */
        DepthOfFieldEffect.prototype._updateEffects = function () {
            for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
                this._effects[effectIndex].updateEffect();
            }
        };
        /**
         * Internal
         * @returns if all the contained post processes are ready.
         * @hidden
         */
        DepthOfFieldEffect.prototype._isReady = function () {
            for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
                if (!this._effects[effectIndex].isReady()) {
                    return false;
                }
            }
            return true;
        };
        return DepthOfFieldEffect;
    }(BABYLON.PostProcessRenderEffect));
    BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.depthOfFieldEffect.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
     */
    var BloomMergePostProcess = /** @class */ (function (_super) {
        __extends(BloomMergePostProcess, _super);
        /**
         * Creates a new instance of @see BloomMergePostProcess
         * @param name The name of the effect.
         * @param originalFromInput Post process which's input will be used for the merge.
         * @param blurred Blurred highlights post process which's output will be used.
         * @param weight Weight of the bloom to be added to the original input.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function BloomMergePostProcess(name, originalFromInput, blurred, 
        /** Weight of the bloom to be added to the original input. */
        weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
            _this.weight = weight;
            _this.onApplyObservable.add(function (effect) {
                effect.setTextureFromPostProcess("textureSampler", originalFromInput);
                effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
                effect.setFloat("bloomWeight", _this.weight);
            });
            if (!blockCompilation) {
                _this.updateEffect();
            }
            return _this;
        }
        return BloomMergePostProcess;
    }(BABYLON.PostProcess));
    BABYLON.BloomMergePostProcess = BloomMergePostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.bloomMergePostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The extract highlights post process sets all pixels to black except pixels above the specified luminance threshold. Used as the first step for a bloom effect.
     */
    var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
        __extends(ExtractHighlightsPostProcess, _super);
        function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
            /**
             * The luminance threshold, pixels below this value will be set to black.
             */
            _this.threshold = 0.9;
            /** @hidden */
            _this._exposure = 1;
            /**
             * Post process which has the input texture to be used when performing highlight extraction
             * @hidden
             */
            _this._inputPostProcess = null;
            _this.onApplyObservable.add(function (effect) {
                if (_this._inputPostProcess) {
                    effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
                }
                effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
                effect.setFloat('exposure', _this._exposure);
            });
            return _this;
        }
        return ExtractHighlightsPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
     */
    var BloomEffect = /** @class */ (function (_super) {
        __extends(BloomEffect, _super);
        /**
         * Creates a new instance of @see BloomEffect
         * @param scene The scene the effect belongs to.
         * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
         * @param bloomKernel The size of the kernel to be used when applying the blur.
         * @param bloomWeight The the strength of bloom.
         * @param pipelineTextureType The type of texture to be used when performing the post processing.
         * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
         */
        function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
            if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
            if (blockCompilation === void 0) { blockCompilation = false; }
            var _this = _super.call(this, scene.getEngine(), "bloom", function () {
                return _this._effects;
            }, true) || this;
            _this.bloomScale = bloomScale;
            /**
             * @hidden Internal
             */
            _this._effects = [];
            _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
            _this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
            _this._blurX.alwaysForcePOT = true;
            _this._blurX.autoClear = false;
            _this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, undefined, blockCompilation);
            _this._blurY.alwaysForcePOT = true;
            _this._blurY.autoClear = false;
            _this.kernel = bloomKernel;
            _this._effects = [_this._downscale, _this._blurX, _this._blurY];
            _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
            _this._merge.autoClear = false;
            _this._effects.push(_this._merge);
            return _this;
        }
        Object.defineProperty(BloomEffect.prototype, "threshold", {
            /**
             * The luminance threshold to find bright areas of the image to bloom.
             */
            get: function () {
                return this._downscale.threshold;
            },
            set: function (value) {
                this._downscale.threshold = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BloomEffect.prototype, "weight", {
            /**
             * The strength of the bloom.
             */
            get: function () {
                return this._merge.weight;
            },
            set: function (value) {
                this._merge.weight = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BloomEffect.prototype, "kernel", {
            /**
             * Specifies the size of the bloom blur kernel, relative to the final output size
             */
            get: function () {
                return this._blurX.kernel / this.bloomScale;
            },
            set: function (value) {
                this._blurX.kernel = value * this.bloomScale;
                this._blurY.kernel = value * this.bloomScale;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes each of the internal effects for a given camera.
         * @param camera The camera to dispose the effect on.
         */
        BloomEffect.prototype.disposeEffects = function (camera) {
            for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
                this._effects[effectIndex].dispose(camera);
            }
        };
        /**
         * @hidden Internal
         */
        BloomEffect.prototype._updateEffects = function () {
            for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
                this._effects[effectIndex].updateEffect();
            }
        };
        /**
         * Internal
         * @returns if all the contained post processes are ready.
         * @hidden
         */
        BloomEffect.prototype._isReady = function () {
            for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
                if (!this._effects[effectIndex].isReady()) {
                    return false;
                }
            }
            return true;
        };
        return BloomEffect;
    }(BABYLON.PostProcessRenderEffect));
    BABYLON.BloomEffect = BloomEffect;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.bloomEffect.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
     * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
     */
    var DefaultRenderingPipeline = /** @class */ (function (_super) {
        __extends(DefaultRenderingPipeline, _super);
        /**
         * @constructor
         * @param name - The rendering pipeline name (default: "")
         * @param hdr - If high dynamic range textures should be used (default: true)
         * @param scene - The scene linked to this pipeline (default: the last created scene)
         * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
         * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
         */
        function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
            if (name === void 0) { name = ""; }
            if (hdr === void 0) { hdr = true; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            if (automaticBuild === void 0) { automaticBuild = true; }
            var _this = _super.call(this, scene.getEngine(), name) || this;
            _this._camerasToBeAttached = [];
            /**
             * ID of the sharpen post process,
             */
            _this.SharpenPostProcessId = "SharpenPostProcessEffect";
            /**
             * @ignore
             * ID of the image processing post process;
             */
            _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
            /**
             * @ignore
             * ID of the Fast Approximate Anti-Aliasing post process;
             */
            _this.FxaaPostProcessId = "FxaaPostProcessEffect";
            /**
             * ID of the chromatic aberration post process,
             */
            _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
            /**
             * ID of the grain post process
             */
            _this.GrainPostProcessId = "GrainPostProcessEffect";
            /**
             * Glow post process which adds a glow to emmisive areas of the image
             */
            _this._glowLayer = null;
            /**
             * Animations which can be used to tweak settings over a period of time
             */
            _this.animations = [];
            _this._imageProcessingConfigurationObserver = null;
            // Values
            _this._sharpenEnabled = false;
            _this._bloomEnabled = false;
            _this._depthOfFieldEnabled = false;
            _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
            _this._fxaaEnabled = false;
            _this._imageProcessingEnabled = true;
            _this._bloomScale = 0.5;
            _this._chromaticAberrationEnabled = false;
            _this._grainEnabled = false;
            _this._buildAllowed = true;
            _this._resizeObserver = null;
            _this._hardwareScaleLevel = 1.0;
            _this._bloomKernel = 64;
            /**
             * Specifies the weight of the bloom in the final rendering
             */
            _this._bloomWeight = 0.15;
            /**
             * Specifies the luma threshold for the area that will be blurred by the bloom
             */
            _this._bloomThreshold = 0.9;
            _this._samples = 1;
            _this._hasCleared = false;
            _this._prevPostProcess = null;
            _this._prevPrevPostProcess = null;
            _this._depthOfFieldSceneObserver = null;
            _this._cameras = cameras || scene.cameras;
            _this._cameras = _this._cameras.slice();
            _this._camerasToBeAttached = _this._cameras.slice();
            _this._buildAllowed = automaticBuild;
            // Initialize
            _this._scene = scene;
            var caps = _this._scene.getEngine().getCaps();
            _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
            // Misc
            if (_this._hdr) {
                if (caps.textureHalfFloatRender) {
                    _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                }
                else if (caps.textureFloatRender) {
                    _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
                }
            }
            else {
                _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            }
            // Attach
            scene.postProcessRenderPipelineManager.addPipeline(_this);
            var engine = _this._scene.getEngine();
            // Create post processes before hand so they can be modified before enabled.
            // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
            _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
            _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
            _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
            _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
            _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
            _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
            _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
            _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
            _this._resizeObserver = engine.onResizeObservable.add(function () {
                _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
                _this.bloomKernel = _this.bloomKernel;
            });
            _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
                _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
            });
            _this._buildPipeline();
            return _this;
        }
        Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
            get: function () {
                return this._sharpenEnabled;
            },
            /**
             * Enable or disable the sharpen process from the pipeline
             */
            set: function (enabled) {
                if (this._sharpenEnabled === enabled) {
                    return;
                }
                this._sharpenEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
            /**
             * Specifies the size of the bloom blur kernel, relative to the final output size
             */
            get: function () {
                return this._bloomKernel;
            },
            set: function (value) {
                this._bloomKernel = value;
                this.bloom.kernel = value / this._hardwareScaleLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
            get: function () {
                return this._bloomWeight;
            },
            /**
             * The strength of the bloom.
             */
            set: function (value) {
                if (this._bloomWeight === value) {
                    return;
                }
                this.bloom.weight = value;
                this._bloomWeight = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
            get: function () {
                return this._bloomThreshold;
            },
            /**
             * The strength of the bloom.
             */
            set: function (value) {
                if (this._bloomThreshold === value) {
                    return;
                }
                this.bloom.threshold = value;
                this._bloomThreshold = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
            get: function () {
                return this._bloomScale;
            },
            /**
             * The scale of the bloom, lower value will provide better performance.
             */
            set: function (value) {
                if (this._bloomScale === value) {
                    return;
                }
                this._bloomScale = value;
                // recreate bloom and dispose old as this setting is not dynamic
                this._rebuildBloom();
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
            get: function () {
                return this._bloomEnabled;
            },
            /**
             * Enable or disable the bloom from the pipeline
             */
            set: function (enabled) {
                if (this._bloomEnabled === enabled) {
                    return;
                }
                this._bloomEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        DefaultRenderingPipeline.prototype._rebuildBloom = function () {
            // recreate bloom and dispose old as this setting is not dynamic
            var oldBloom = this.bloom;
            this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
            this.bloom.threshold = oldBloom.threshold;
            for (var i = 0; i < this._cameras.length; i++) {
                oldBloom.disposeEffects(this._cameras[i]);
            }
        };
        Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
            /**
             * If the depth of field is enabled.
             */
            get: function () {
                return this._depthOfFieldEnabled;
            },
            set: function (enabled) {
                if (this._depthOfFieldEnabled === enabled) {
                    return;
                }
                this._depthOfFieldEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
            /**
             * Blur level of the depth of field effect. (Higher blur will effect performance)
             */
            get: function () {
                return this._depthOfFieldBlurLevel;
            },
            set: function (value) {
                if (this._depthOfFieldBlurLevel === value) {
                    return;
                }
                this._depthOfFieldBlurLevel = value;
                // recreate dof and dispose old as this setting is not dynamic
                var oldDof = this.depthOfField;
                this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
                this.depthOfField.focalLength = oldDof.focalLength;
                this.depthOfField.focusDistance = oldDof.focusDistance;
                this.depthOfField.fStop = oldDof.fStop;
                this.depthOfField.lensSize = oldDof.lensSize;
                for (var i = 0; i < this._cameras.length; i++) {
                    oldDof.disposeEffects(this._cameras[i]);
                }
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
            get: function () {
                return this._fxaaEnabled;
            },
            /**
             * If the anti aliasing is enabled.
             */
            set: function (enabled) {
                if (this._fxaaEnabled === enabled) {
                    return;
                }
                this._fxaaEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
            get: function () {
                return this._samples;
            },
            /**
             * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
             */
            set: function (sampleCount) {
                if (this._samples === sampleCount) {
                    return;
                }
                this._samples = sampleCount;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
            get: function () {
                return this._imageProcessingEnabled;
            },
            /**
             * If image processing is enabled.
             */
            set: function (enabled) {
                if (this._imageProcessingEnabled === enabled) {
                    return;
                }
                this._imageProcessingEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
            get: function () {
                return this._glowLayer == null;
            },
            /**
             * If glow layer is enabled. (Adds a glow effect to emmissive materials)
             */
            set: function (enabled) {
                if (enabled && !this._glowLayer) {
                    this._glowLayer = new BABYLON.GlowLayer("", this._scene);
                }
                else if (!enabled && this._glowLayer) {
                    this._glowLayer.dispose();
                    this._glowLayer = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
            get: function () {
                return this._chromaticAberrationEnabled;
            },
            /**
             * Enable or disable the chromaticAberration process from the pipeline
             */
            set: function (enabled) {
                if (this._chromaticAberrationEnabled === enabled) {
                    return;
                }
                this._chromaticAberrationEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
            get: function () {
                return this._grainEnabled;
            },
            /**
             * Enable or disable the grain process from the pipeline
             */
            set: function (enabled) {
                if (this._grainEnabled === enabled) {
                    return;
                }
                this._grainEnabled = enabled;
                this._buildPipeline();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Force the compilation of the entire pipeline.
         */
        DefaultRenderingPipeline.prototype.prepare = function () {
            var previousState = this._buildAllowed;
            this._buildAllowed = true;
            this._buildPipeline();
            this._buildAllowed = previousState;
        };
        DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
            if (skipTextureSharing === void 0) { skipTextureSharing = false; }
            if (this._hasCleared) {
                postProcess.autoClear = false;
            }
            else {
                postProcess.autoClear = true;
                this._scene.autoClear = false;
                this._hasCleared = true;
            }
            if (!skipTextureSharing) {
                if (this._prevPrevPostProcess) {
                    postProcess.shareOutputWith(this._prevPrevPostProcess);
                }
                else {
                    postProcess.useOwnOutput();
                }
                if (this._prevPostProcess) {
                    this._prevPrevPostProcess = this._prevPostProcess;
                }
                this._prevPostProcess = postProcess;
            }
        };
        DefaultRenderingPipeline.prototype._buildPipeline = function () {
            var _this = this;
            if (!this._buildAllowed) {
                return;
            }
            this._scene.autoClear = true;
            var engine = this._scene.getEngine();
            this._disposePostProcesses();
            if (this._cameras !== null) {
                this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
                // get back cameras to be used to reattach pipeline
                this._cameras = this._camerasToBeAttached.slice();
            }
            this._reset();
            this._prevPostProcess = null;
            this._prevPrevPostProcess = null;
            this._hasCleared = false;
            if (this.depthOfFieldEnabled) {
                // Multi camera suport
                if (this._cameras.length > 1) {
                    for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
                        var camera = _a[_i];
                        var depthRenderer = this._scene.enableDepthRenderer(camera);
                        depthRenderer.useOnlyInActiveCamera = true;
                    }
                    this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
                        if (_this._cameras.indexOf(scene.activeCamera) > -1) {
                            _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
                        }
                    });
                }
                else {
                    this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
                    var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
                    this.depthOfField.depthTexture = depthRenderer.getDepthMap();
                }
                if (!this.depthOfField._isReady()) {
                    this.depthOfField._updateEffects();
                }
                this.addEffect(this.depthOfField);
                this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
            }
            else {
                this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
            }
            if (this.bloomEnabled) {
                if (!this.bloom._isReady()) {
                    this.bloom._updateEffects();
                }
                this.addEffect(this.bloom);
                this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
            }
            if (this._imageProcessingEnabled) {
                this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
                if (this._hdr) {
                    this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
                    this._setAutoClearAndTextureSharing(this.imageProcessing);
                }
                else {
                    this._scene.imageProcessingConfiguration.applyByPostProcess = false;
                }
            }
            if (this.sharpenEnabled) {
                if (!this.sharpen.isReady()) {
                    this.sharpen.updateEffect();
                }
                this.addEffect(this._sharpenEffect);
                this._setAutoClearAndTextureSharing(this.sharpen);
            }
            if (this.grainEnabled) {
                if (!this.grain.isReady()) {
                    this.grain.updateEffect();
                }
                this.addEffect(this._grainEffect);
                this._setAutoClearAndTextureSharing(this.grain);
            }
            if (this.chromaticAberrationEnabled) {
                if (!this.chromaticAberration.isReady()) {
                    this.chromaticAberration.updateEffect();
                }
                this.addEffect(this._chromaticAberrationEffect);
                this._setAutoClearAndTextureSharing(this.chromaticAberration);
            }
            if (this.fxaaEnabled) {
                this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
                this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
                this._setAutoClearAndTextureSharing(this.fxaa, true);
            }
            if (this._cameras !== null) {
                this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
            }
            if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
                BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
            }
        };
        DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
            if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
            for (var i = 0; i < this._cameras.length; i++) {
                var camera = this._cameras[i];
                if (this.imageProcessing) {
                    this.imageProcessing.dispose(camera);
                }
                if (this.fxaa) {
                    this.fxaa.dispose(camera);
                }
                // These are created in the constructor and should not be disposed on every pipeline change
                if (disposeNonRecreated) {
                    if (this.sharpen) {
                        this.sharpen.dispose(camera);
                    }
                    if (this.depthOfField) {
                        this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
                        this.depthOfField.disposeEffects(camera);
                    }
                    if (this.bloom) {
                        this.bloom.disposeEffects(camera);
                    }
                    if (this.chromaticAberration) {
                        this.chromaticAberration.dispose(camera);
                    }
                    if (this.grain) {
                        this.grain.dispose(camera);
                    }
                    if (this._glowLayer) {
                        this._glowLayer.dispose();
                    }
                }
            }
            this.imageProcessing = null;
            this.fxaa = null;
            if (disposeNonRecreated) {
                this.sharpen = null;
                this._sharpenEffect = null;
                this.depthOfField = null;
                this.bloom = null;
                this.chromaticAberration = null;
                this._chromaticAberrationEffect = null;
                this.grain = null;
                this._grainEffect = null;
                this._glowLayer = null;
            }
        };
        /**
         * Adds a camera to the pipeline
         * @param camera the camera to be added
         */
        DefaultRenderingPipeline.prototype.addCamera = function (camera) {
            this._camerasToBeAttached.push(camera);
            this._buildPipeline();
        };
        /**
         * Removes a camera from the pipeline
         * @param camera the camera to remove
         */
        DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
            var index = this._camerasToBeAttached.indexOf(camera);
            this._camerasToBeAttached.splice(index, 1);
            this._buildPipeline();
        };
        /**
         * Dispose of the pipeline and stop all post processes
         */
        DefaultRenderingPipeline.prototype.dispose = function () {
            this._disposePostProcesses(true);
            this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
            this._scene.autoClear = true;
            if (this._resizeObserver) {
                this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
                this._resizeObserver = null;
            }
            this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
            _super.prototype.dispose.call(this);
        };
        /**
         * Serialize the rendering pipeline (Used when exporting)
         * @returns the serialized object
         */
        DefaultRenderingPipeline.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "DefaultRenderingPipeline";
            return serializationObject;
        };
        /**
         * Parse the serialized pipeline
         * @param source Source pipeline.
         * @param scene The scene to load the pipeline to.
         * @param rootUrl The URL of the serialized pipeline.
         * @returns An instantiated pipeline from the serialized object.
         */
        DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
        };
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "bloomScale", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "samples", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
        __decorate([
            BABYLON.serialize()
        ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
        return DefaultRenderingPipeline;
    }(BABYLON.PostProcessRenderPipeline));
    BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.defaultRenderingPipeline.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     */
    var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
        __extends(ImageProcessingConfigurationDefines, _super);
        function ImageProcessingConfigurationDefines() {
            var _this = _super.call(this) || this;
            _this.IMAGEPROCESSING = false;
            _this.VIGNETTE = false;
            _this.VIGNETTEBLENDMODEMULTIPLY = false;
            _this.VIGNETTEBLENDMODEOPAQUE = false;
            _this.TONEMAPPING = false;
            _this.TONEMAPPING_ACES = false;
            _this.CONTRAST = false;
            _this.COLORCURVES = false;
            _this.COLORGRADING = false;
            _this.COLORGRADING3D = false;
            _this.SAMPLER3DGREENDEPTH = false;
            _this.SAMPLER3DBGRMAP = false;
            _this.IMAGEPROCESSINGPOSTPROCESS = false;
            _this.EXPOSURE = false;
            _this.rebuild();
            return _this;
        }
        return ImageProcessingConfigurationDefines;
    }(BABYLON.MaterialDefines));
    BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
    /**
     * This groups together the common properties used for image processing either in direct forward pass
     * or through post processing effect depending on the use of the image processing pipeline in your scene
     * or not.
     */
    var ImageProcessingConfiguration = /** @class */ (function () {
        function ImageProcessingConfiguration() {
            /**
             * Color curves setup used in the effect if colorCurvesEnabled is set to true
             */
            this.colorCurves = new BABYLON.ColorCurves();
            this._colorCurvesEnabled = false;
            this._colorGradingEnabled = false;
            this._colorGradingWithGreenDepth = true;
            this._colorGradingBGR = true;
            /** @hidden */
            this._exposure = 1.0;
            this._toneMappingEnabled = false;
            this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
            this._contrast = 1.0;
            /**
             * Vignette stretch size.
             */
            this.vignetteStretch = 0;
            /**
             * Vignette centre X Offset.
             */
            this.vignetteCentreX = 0;
            /**
             * Vignette centre Y Offset.
             */
            this.vignetteCentreY = 0;
            /**
             * Vignette weight or intensity of the vignette effect.
             */
            this.vignetteWeight = 1.5;
            /**
             * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
             * if vignetteEnabled is set to true.
             */
            this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
            /**
             * Camera field of view used by the Vignette effect.
             */
            this.vignetteCameraFov = 0.5;
            this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
            this._vignetteEnabled = false;
            this._applyByPostProcess = false;
            this._isEnabled = true;
            /**
            * An event triggered when the configuration changes and requires Shader to Update some parameters.
            */
            this.onUpdateParameters = new BABYLON.Observable();
        }
        Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
            /**
             * Gets wether the color curves effect is enabled.
             */
            get: function () {
                return this._colorCurvesEnabled;
            },
            /**
             * Sets wether the color curves effect is enabled.
             */
            set: function (value) {
                if (this._colorCurvesEnabled === value) {
                    return;
                }
                this._colorCurvesEnabled = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
            /**
             * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
             */
            get: function () {
                return this._colorGradingTexture;
            },
            /**
             * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
             */
            set: function (value) {
                if (this._colorGradingTexture === value) {
                    return;
                }
                this._colorGradingTexture = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
            /**
             * Gets wether the color grading effect is enabled.
             */
            get: function () {
                return this._colorGradingEnabled;
            },
            /**
             * Sets wether the color grading effect is enabled.
             */
            set: function (value) {
                if (this._colorGradingEnabled === value) {
                    return;
                }
                this._colorGradingEnabled = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
            /**
             * Gets wether the color grading effect is using a green depth for the 3d Texture.
             */
            get: function () {
                return this._colorGradingWithGreenDepth;
            },
            /**
             * Sets wether the color grading effect is using a green depth for the 3d Texture.
             */
            set: function (value) {
                if (this._colorGradingWithGreenDepth === value) {
                    return;
                }
                this._colorGradingWithGreenDepth = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
            /**
             * Gets wether the color grading texture contains BGR values.
             */
            get: function () {
                return this._colorGradingBGR;
            },
            /**
             * Sets wether the color grading texture contains BGR values.
             */
            set: function (value) {
                if (this._colorGradingBGR === value) {
                    return;
                }
                this._colorGradingBGR = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
            /**
             * Gets the Exposure used in the effect.
             */
            get: function () {
                return this._exposure;
            },
            /**
             * Sets the Exposure used in the effect.
             */
            set: function (value) {
                if (this._exposure === value) {
                    return;
                }
                this._exposure = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
            /**
             * Gets wether the tone mapping effect is enabled.
             */
            get: function () {
                return this._toneMappingEnabled;
            },
            /**
             * Sets wether the tone mapping effect is enabled.
             */
            set: function (value) {
                if (this._toneMappingEnabled === value) {
                    return;
                }
                this._toneMappingEnabled = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
            /**
             * Gets the type of tone mapping effect.
             */
            get: function () {
                return this._toneMappingType;
            },
            /**
             * Sets the type of tone mapping effect used in BabylonJS.
             */
            set: function (value) {
                if (this._toneMappingType === value) {
                    return;
                }
                this._toneMappingType = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
            /**
             * Gets the contrast used in the effect.
             */
            get: function () {
                return this._contrast;
            },
            /**
             * Sets the contrast used in the effect.
             */
            set: function (value) {
                if (this._contrast === value) {
                    return;
                }
                this._contrast = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
            /**
             * Gets the vignette blend mode allowing different kind of effect.
             */
            get: function () {
                return this._vignetteBlendMode;
            },
            /**
             * Sets the vignette blend mode allowing different kind of effect.
             */
            set: function (value) {
                if (this._vignetteBlendMode === value) {
                    return;
                }
                this._vignetteBlendMode = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
            /**
             * Gets wether the vignette effect is enabled.
             */
            get: function () {
                return this._vignetteEnabled;
            },
            /**
             * Sets wether the vignette effect is enabled.
             */
            set: function (value) {
                if (this._vignetteEnabled === value) {
                    return;
                }
                this._vignetteEnabled = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
            /**
             * Gets wether the image processing is applied through a post process or not.
             */
            get: function () {
                return this._applyByPostProcess;
            },
            /**
             * Sets wether the image processing is applied through a post process or not.
             */
            set: function (value) {
                if (this._applyByPostProcess === value) {
                    return;
                }
                this._applyByPostProcess = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
            /**
             * Gets wether the image processing is enabled or not.
             */
            get: function () {
                return this._isEnabled;
            },
            /**
             * Sets wether the image processing is enabled or not.
             */
            set: function (value) {
                if (this._isEnabled === value) {
                    return;
                }
                this._isEnabled = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Method called each time the image processing information changes requires to recompile the effect.
         */
        ImageProcessingConfiguration.prototype._updateParameters = function () {
            this.onUpdateParameters.notifyObservers(this);
        };
        /**
         * Gets the current class name.
         * @return "ImageProcessingConfiguration"
         */
        ImageProcessingConfiguration.prototype.getClassName = function () {
            return "ImageProcessingConfiguration";
        };
        /**
         * Prepare the list of uniforms associated with the Image Processing effects.
         * @param uniforms The list of uniforms used in the effect
         * @param defines the list of defines currently in use
         */
        ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
            if (defines.EXPOSURE) {
                uniforms.push("exposureLinear");
            }
            if (defines.CONTRAST) {
                uniforms.push("contrast");
            }
            if (defines.COLORGRADING) {
                uniforms.push("colorTransformSettings");
            }
            if (defines.VIGNETTE) {
                uniforms.push("vInverseScreenSize");
                uniforms.push("vignetteSettings1");
                uniforms.push("vignetteSettings2");
            }
            if (defines.COLORCURVES) {
                BABYLON.ColorCurves.PrepareUniforms(uniforms);
            }
        };
        /**
         * Prepare the list of samplers associated with the Image Processing effects.
         * @param samplersList The list of uniforms used in the effect
         * @param defines the list of defines currently in use
         */
        ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
            if (defines.COLORGRADING) {
                samplersList.push("txColorTransform");
            }
        };
        /**
         * Prepare the list of defines associated to the shader.
         * @param defines the list of defines to complete
         * @param forPostProcess Define if we are currently in post process mode or not
         */
        ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
            if (forPostProcess === void 0) { forPostProcess = false; }
            if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
                defines.VIGNETTE = false;
                defines.TONEMAPPING = false;
                defines.TONEMAPPING_ACES = false;
                defines.CONTRAST = false;
                defines.EXPOSURE = false;
                defines.COLORCURVES = false;
                defines.COLORGRADING = false;
                defines.COLORGRADING3D = false;
                defines.IMAGEPROCESSING = false;
                defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
                return;
            }
            defines.VIGNETTE = this.vignetteEnabled;
            defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
            defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
            defines.TONEMAPPING = this.toneMappingEnabled;
            switch (this._toneMappingType) {
                case ImageProcessingConfiguration.TONEMAPPING_ACES:
                    defines.TONEMAPPING_ACES = true;
                    break;
            }
            defines.CONTRAST = (this.contrast !== 1.0);
            defines.EXPOSURE = (this.exposure !== 1.0);
            defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
            defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
            if (defines.COLORGRADING) {
                defines.COLORGRADING3D = this.colorGradingTexture.is3D;
            }
            else {
                defines.COLORGRADING3D = false;
            }
            defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
            defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
            defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
            defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
        };
        /**
         * Returns true if all the image processing information are ready.
         * @returns True if ready, otherwise, false
         */
        ImageProcessingConfiguration.prototype.isReady = function () {
            // Color Grading texure can not be none blocking.
            return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
        };
        /**
         * Binds the image processing to the shader.
         * @param effect The effect to bind to
         * @param aspectRatio Define the current aspect ratio of the effect
         */
        ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
            if (aspectRatio === void 0) { aspectRatio = 1; }
            // Color Curves
            if (this._colorCurvesEnabled && this.colorCurves) {
                BABYLON.ColorCurves.Bind(this.colorCurves, effect);
            }
            // Vignette
            if (this._vignetteEnabled) {
                var inverseWidth = 1 / effect.getEngine().getRenderWidth();
                var inverseHeight = 1 / effect.getEngine().getRenderHeight();
                effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
                var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
                var vignetteScaleX = vignetteScaleY * aspectRatio;
                var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
                vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
                vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
                effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
                var vignettePower = -2.0 * this.vignetteWeight;
                effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
            }
            // Exposure
            effect.setFloat("exposureLinear", this.exposure);
            // Contrast
            effect.setFloat("contrast", this.contrast);
            // Color transform settings
            if (this.colorGradingTexture) {
                effect.setTexture("txColorTransform", this.colorGradingTexture);
                var textureSize = this.colorGradingTexture.getSize().height;
                effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
                0.5 / textureSize, // textureOffset
                textureSize, // textureSize
                this.colorGradingTexture.level // weight
                );
            }
        };
        /**
         * Clones the current image processing instance.
         * @return The cloned image processing
         */
        ImageProcessingConfiguration.prototype.clone = function () {
            return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
        };
        /**
         * Serializes the current image processing instance to a json representation.
         * @return a JSON representation
         */
        ImageProcessingConfiguration.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        /**
         * Parses the image processing from a json representation.
         * @param source the JSON source to parse
         * @return The parsed image processing
         */
        ImageProcessingConfiguration.Parse = function (source) {
            return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
        };
        Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
            /**
             * Used to apply the vignette as a mix with the pixel color.
             */
            get: function () {
                return this._VIGNETTEMODE_MULTIPLY;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
            /**
             * Used to apply the vignette as a replacement of the pixel color.
             */
            get: function () {
                return this._VIGNETTEMODE_OPAQUE;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Default tone mapping applied in BabylonJS.
         */
        ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
        /**
         * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
         * to other engines rendering to increase portability.
         */
        ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
        // Static constants associated to the image processing.
        ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
        ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
        __decorate([
            BABYLON.serializeAsColorCurves()
        ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
        __decorate([
            BABYLON.serializeAsTexture("colorGradingTexture")
        ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
        __decorate([
            BABYLON.serializeAsColor4()
        ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
        return ImageProcessingConfiguration;
    }());
    BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.imageProcessingConfiguration.js.map


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

//# sourceMappingURL=babylon.colorGradingTexture.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
     * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
     * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
     * corresponding to low luminance, medium luminance, and high luminance areas respectively.
     */
    var ColorCurves = /** @class */ (function () {
        function ColorCurves() {
            this._dirty = true;
            this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
            this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
            this._globalHue = 30;
            this._globalDensity = 0;
            this._globalSaturation = 0;
            this._globalExposure = 0;
            this._highlightsHue = 30;
            this._highlightsDensity = 0;
            this._highlightsSaturation = 0;
            this._highlightsExposure = 0;
            this._midtonesHue = 30;
            this._midtonesDensity = 0;
            this._midtonesSaturation = 0;
            this._midtonesExposure = 0;
            this._shadowsHue = 30;
            this._shadowsDensity = 0;
            this._shadowsSaturation = 0;
            this._shadowsExposure = 0;
        }
        Object.defineProperty(ColorCurves.prototype, "globalHue", {
            /**
             * Gets the global Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._globalHue;
            },
            /**
             * Sets the global Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._globalHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "globalDensity", {
            /**
             * Gets the global Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._globalDensity;
            },
            /**
             * Sets the global Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._globalDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
            /**
             * Gets the global Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._globalSaturation;
            },
            /**
             * Sets the global Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._globalSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "globalExposure", {
            /**
             * Gets the global Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._globalExposure;
            },
            /**
             * Sets the global Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._globalExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
            /**
             * Gets the highlights Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._highlightsHue;
            },
            /**
             * Sets the highlights Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._highlightsHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
            /**
             * Gets the highlights Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._highlightsDensity;
            },
            /**
             * Sets the highlights Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._highlightsDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
            /**
             * Gets the highlights Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._highlightsSaturation;
            },
            /**
             * Sets the highlights Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._highlightsSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
            /**
             * Gets the highlights Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._highlightsExposure;
            },
            /**
             * Sets the highlights Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._highlightsExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
            /**
             * Gets the midtones Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._midtonesHue;
            },
            /**
             * Sets the midtones Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._midtonesHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
            /**
             * Gets the midtones Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._midtonesDensity;
            },
            /**
             * Sets the midtones Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._midtonesDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
            /**
             * Gets the midtones Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._midtonesSaturation;
            },
            /**
             * Sets the midtones Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._midtonesSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
            /**
             * Gets the midtones Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._midtonesExposure;
            },
            /**
             * Sets the midtones Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._midtonesExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
            /**
             * Gets the shadows Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            get: function () {
                return this._shadowsHue;
            },
            /**
             * Sets the shadows Hue value.
             * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
             */
            set: function (value) {
                this._shadowsHue = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
            /**
             * Gets the shadows Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            get: function () {
                return this._shadowsDensity;
            },
            /**
             * Sets the shadows Density value.
             * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
             * Values less than zero provide a filter of opposite hue.
             */
            set: function (value) {
                this._shadowsDensity = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
            /**
             * Gets the shadows Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            get: function () {
                return this._shadowsSaturation;
            },
            /**
             * Sets the shadows Saturation value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
             */
            set: function (value) {
                this._shadowsSaturation = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
            /**
             * Gets the shadows Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            get: function () {
                return this._shadowsExposure;
            },
            /**
             * Sets the shadows Exposure value.
             * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
             */
            set: function (value) {
                this._shadowsExposure = value;
                this._dirty = true;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the class name
         * @returns The class name
         */
        ColorCurves.prototype.getClassName = function () {
            return "ColorCurves";
        };
        /**
         * Binds the color curves to the shader.
         * @param colorCurves The color curve to bind
         * @param effect The effect to bind to
         * @param positiveUniform The positive uniform shader parameter
         * @param neutralUniform The neutral uniform shader parameter
         * @param negativeUniform The negative uniform shader parameter
         */
        ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
            if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
            if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
            if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
            if (colorCurves._dirty) {
                colorCurves._dirty = false;
                // Fill in global info.
                colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
                // Compute highlights info.
                colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
                colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
                // Compute midtones info.
                colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
                colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
                // Compute shadows info.
                colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
                colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
                // Compute deltas (neutral is midtones).
                colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
                colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
            }
            if (effect) {
                effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
                effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
                effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
            }
        };
        /**
         * Prepare the list of uniforms associated with the ColorCurves effects.
         * @param uniformsList The list of uniforms used in the effect
         */
        ColorCurves.PrepareUniforms = function (uniformsList) {
            uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
        };
        /**
         * Returns color grading data based on a hue, density, saturation and exposure value.
         * @param filterHue The hue of the color filter.
         * @param filterDensity The density of the color filter.
         * @param saturation The saturation.
         * @param exposure The exposure.
         * @param result The result data container.
         */
        ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
            if (hue == null) {
                return;
            }
            hue = ColorCurves.clamp(hue, 0, 360);
            density = ColorCurves.clamp(density, -100, 100);
            saturation = ColorCurves.clamp(saturation, -100, 100);
            exposure = ColorCurves.clamp(exposure, -100, 100);
            // Remap the slider/config filter density with non-linear mapping and also scale by half
            // so that the maximum filter density is only 50% control. This provides fine control
            // for small values and reasonable range.
            density = ColorCurves.applyColorGradingSliderNonlinear(density);
            density *= 0.5;
            exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
            if (density < 0) {
                density *= -1;
                hue = (hue + 180) % 360;
            }
            ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
            result.scaleToRef(2, result);
            result.a = 1 + 0.01 * saturation;
        };
        /**
         * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
         * @param value The input slider value in range [-100,100].
         * @returns Adjusted value.
         */
        ColorCurves.applyColorGradingSliderNonlinear = function (value) {
            value /= 100;
            var x = Math.abs(value);
            x = Math.pow(x, 2);
            if (value < 0) {
                x *= -1;
            }
            x *= 100;
            return x;
        };
        /**
         * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
         * @param hue The hue (H) input.
         * @param saturation The saturation (S) input.
         * @param brightness The brightness (B) input.
         * @result An RGBA color represented as Vector4.
         */
        ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
            var h = ColorCurves.clamp(hue, 0, 360);
            var s = ColorCurves.clamp(saturation / 100, 0, 1);
            var v = ColorCurves.clamp(brightness / 100, 0, 1);
            if (s === 0) {
                result.r = v;
                result.g = v;
                result.b = v;
            }
            else {
                // sector 0 to 5
                h /= 60;
                var i = Math.floor(h);
                // fractional part of h
                var f = h - i;
                var p = v * (1 - s);
                var q = v * (1 - s * f);
                var t = v * (1 - s * (1 - f));
                switch (i) {
                    case 0:
                        result.r = v;
                        result.g = t;
                        result.b = p;
                        break;
                    case 1:
                        result.r = q;
                        result.g = v;
                        result.b = p;
                        break;
                    case 2:
                        result.r = p;
                        result.g = v;
                        result.b = t;
                        break;
                    case 3:
                        result.r = p;
                        result.g = q;
                        result.b = v;
                        break;
                    case 4:
                        result.r = t;
                        result.g = p;
                        result.b = v;
                        break;
                    default: // case 5:
                        result.r = v;
                        result.g = p;
                        result.b = q;
                        break;
                }
            }
            result.a = 1;
        };
        /**
         * Returns a value clamped between min and max
         * @param value The value to clamp
         * @param min The minimum of value
         * @param max The maximum of value
         * @returns The clamped value.
         */
        ColorCurves.clamp = function (value, min, max) {
            return Math.min(Math.max(value, min), max);
        };
        /**
         * Clones the current color curve instance.
         * @return The cloned curves
         */
        ColorCurves.prototype.clone = function () {
            return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
        };
        /**
         * Serializes the current color curve instance to a json representation.
         * @return a JSON representation
         */
        ColorCurves.prototype.serialize = function () {
            return BABYLON.SerializationHelper.Serialize(this);
        };
        /**
         * Parses the color curve from a json representation.
         * @param source the JSON source to parse
         * @return The parsed curves
         */
        ColorCurves.Parse = function (source) {
            return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
        };
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalHue", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalDensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalSaturation", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_globalExposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsHue", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsDensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsSaturation", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_highlightsExposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesHue", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesDensity", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesSaturation", void 0);
        __decorate([
            BABYLON.serialize()
        ], ColorCurves.prototype, "_midtonesExposure", void 0);
        return ColorCurves;
    }());
    BABYLON.ColorCurves = ColorCurves;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.colorCurves.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Post process which applies a refractin texture
     * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
     */
    var RefractionPostProcess = /** @class */ (function (_super) {
        __extends(RefractionPostProcess, _super);
        /**
         * Initializes the RefractionPostProcess
         * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
         * @param name The name of the effect.
         * @param refractionTextureUrl Url of the refraction texture to use
         * @param color the base color of the refraction (used to taint the rendering)
         * @param depth simulated refraction depth
         * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
         * @param camera The camera to apply the render pass to.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         */
        function RefractionPostProcess(name, refractionTextureUrl, 
        /** the base color of the refraction (used to taint the rendering) */
        color, 
        /** simulated refraction depth */
        depth, 
        /** the coefficient of the base color (0 to remove base color tainting) */
        colorLevel, options, camera, samplingMode, engine, reusable) {
            var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
            _this.color = color;
            _this.depth = depth;
            _this.colorLevel = colorLevel;
            _this._ownRefractionTexture = true;
            _this.onActivateObservable.add(function (cam) {
                _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
            });
            _this.onApplyObservable.add(function (effect) {
                effect.setColor3("baseColor", _this.color);
                effect.setFloat("depth", _this.depth);
                effect.setFloat("colorLevel", _this.colorLevel);
                effect.setTexture("refractionSampler", _this._refTexture);
            });
            return _this;
        }
        Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
            /**
             * Gets or sets the refraction texture
             * Please note that you are responsible for disposing the texture if you set it manually
             */
            get: function () {
                return this._refTexture;
            },
            set: function (value) {
                if (this._refTexture && this._ownRefractionTexture) {
                    this._refTexture.dispose();
                }
                this._refTexture = value;
                this._ownRefractionTexture = false;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * Disposes of the post process
         * @param camera Camera to dispose post process on
         */
        RefractionPostProcess.prototype.dispose = function (camera) {
            if (this._refTexture && this._ownRefractionTexture) {
                this._refTexture.dispose();
                this._refTexture = null;
            }
            _super.prototype.dispose.call(this, camera);
        };
        return RefractionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.RefractionPostProcess = RefractionPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.refractionPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Post process used to render in black and white
     */
    var BlackAndWhitePostProcess = /** @class */ (function (_super) {
        __extends(BlackAndWhitePostProcess, _super);
        /**
         * Creates a black and white post process
         * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
         * @param name The name of the effect.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         */
        function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
            var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
            /**
             * Linear about to convert he result to black and white (default: 1)
             */
            _this.degree = 1;
            _this.onApplyObservable.add(function (effect) {
                effect.setFloat("degree", _this.degree);
            });
            return _this;
        }
        return BlackAndWhitePostProcess;
    }(BABYLON.PostProcess));
    BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
     * input texture to perform effects such as edge detection or sharpening
     * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
     */
    var ConvolutionPostProcess = /** @class */ (function (_super) {
        __extends(ConvolutionPostProcess, _super);
        /**
         * Creates a new instance ConvolutionPostProcess
         * @param name The name of the effect.
         * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of textures used when performing the post process. (default: 0)
         */
        function ConvolutionPostProcess(name, 
        /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
        kernel, options, camera, samplingMode, engine, reusable, textureType) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
            _this.kernel = kernel;
            _this.onApply = function (effect) {
                effect.setFloat2("screenSize", _this.width, _this.height);
                effect.setArray("kernel", _this.kernel);
            };
            return _this;
        }
        // Statics
        /**
         * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
         */
        ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
        /**
         * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
         */
        ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
        /**
         * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
         */
        ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
        /**
         * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
         */
        ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
        /**
         * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
         */
        ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
        /**
         * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
         */
        ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
        return ConvolutionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.convolutionPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Applies a kernel filter to the image
     */
    var FilterPostProcess = /** @class */ (function (_super) {
        __extends(FilterPostProcess, _super);
        /**
         *
         * @param name The name of the effect.
         * @param kernelMatrix The matrix to be applied to the image
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         */
        function FilterPostProcess(name, 
        /** The matrix to be applied to the image */
        kernelMatrix, options, camera, samplingMode, engine, reusable) {
            var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
            _this.kernelMatrix = kernelMatrix;
            _this.onApply = function (effect) {
                effect.setMatrix("kernelMatrix", _this.kernelMatrix);
            };
            return _this;
        }
        return FilterPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.FilterPostProcess = FilterPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.filterPostProcess.js.map







var BABYLON;
(function (BABYLON) {
    /**
     *  Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
     */
    var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
        __extends(VolumetricLightScatteringPostProcess, _super);
        /**
         * @constructor
         * @param name The post-process name
         * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
         * @param camera The camera that the post-process will be attached to
         * @param mesh The mesh used to create the light scattering
         * @param samples The post-process quality, default 100
         * @param samplingModeThe post-process filtering mode
         * @param engine The babylon engine
         * @param reusable If the post-process is reusable
         * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
         */
        function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
            if (samples === void 0) { samples = 100; }
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
            _this._screenCoordinates = BABYLON.Vector2.Zero();
            /**
            * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
            */
            _this.customMeshPosition = BABYLON.Vector3.Zero();
            /**
            * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
            */
            _this.useCustomMeshPosition = false;
            /**
            * If the post-process should inverse the light scattering direction
            */
            _this.invert = true;
            /**
            * Array containing the excluded meshes not rendered in the internal pass
            */
            _this.excludedMeshes = new Array();
            /**
            * Controls the overall intensity of the post-process
            */
            _this.exposure = 0.3;
            /**
            * Dissipates each sample's contribution in range [0, 1]
            */
            _this.decay = 0.96815;
            /**
            * Controls the overall intensity of each sample
            */
            _this.weight = 0.58767;
            /**
            * Controls the density of each sample
            */
            _this.density = 0.926;
            scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
            engine = scene.getEngine();
            _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
            // Configure mesh
            _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
            // Configure
            _this._createPass(scene, ratio.passRatio || ratio);
            _this.onActivate = function (camera) {
                if (!_this.isSupported) {
                    _this.dispose(camera);
                }
                _this.onActivate = null;
            };
            _this.onApplyObservable.add(function (effect) {
                _this._updateMeshScreenCoordinates(scene);
                effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
                effect.setFloat("exposure", _this.exposure);
                effect.setFloat("decay", _this.decay);
                effect.setFloat("weight", _this.weight);
                effect.setFloat("density", _this.density);
                effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
            });
            return _this;
        }
        Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
            /**
             * @hidden
             * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
             */
            get: function () {
                BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
                return false;
            },
            set: function (useDiffuseColor) {
                BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Returns the string "VolumetricLightScatteringPostProcess"
         * @returns "VolumetricLightScatteringPostProcess"
         */
        VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
            return "VolumetricLightScatteringPostProcess";
        };
        VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
            var mesh = subMesh.getMesh();
            // Render this.mesh as default
            if (mesh === this.mesh && mesh.material) {
                return mesh.material.isReady(mesh);
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var material = subMesh.getMaterial();
            // Alpha test
            if (material) {
                if (material.needAlphaTesting()) {
                    defines.push("#define ALPHATEST");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                    defines.push("#define UV1");
                }
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                    defines.push("#define UV2");
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
            }
            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._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
            }
            return this._volumetricLightScatteringPass.isReady();
        };
        /**
         * Sets the new light position for light scattering effect
         * @param position The new custom light position
         */
        VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
            this.customMeshPosition = position;
        };
        /**
         * Returns the light position for light scattering effect
         * @return Vector3 The custom light position
         */
        VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
            return this.customMeshPosition;
        };
        /**
         * Disposes the internal assets and detaches the post-process from the camera
         */
        VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
            var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
            if (rttIndex !== -1) {
                camera.getScene().customRenderTargets.splice(rttIndex, 1);
            }
            this._volumetricLightScatteringRTT.dispose();
            _super.prototype.dispose.call(this, camera);
        };
        /**
         * Returns the render target texture used by the post-process
         * @return the render target texture used by the post-process
         */
        VolumetricLightScatteringPostProcess.prototype.getPass = function () {
            return this._volumetricLightScatteringRTT;
        };
        // Private methods
        VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
            if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
                return true;
            }
            return false;
        };
        VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
            var _this = this;
            var engine = scene.getEngine();
            this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._volumetricLightScatteringRTT.renderList = null;
            this._volumetricLightScatteringRTT.renderParticles = false;
            this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
            var camera = this.getCamera();
            if (camera) {
                camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
            }
            else {
                scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
            }
            // Custom render function for submeshes
            var renderSubMesh = function (subMesh) {
                var mesh = subMesh.getRenderingMesh();
                if (_this._meshExcluded(mesh)) {
                    return;
                }
                var material = subMesh.getMaterial();
                if (!material) {
                    return;
                }
                var scene = mesh.getScene();
                var engine = scene.getEngine();
                // Culling
                engine.setState(material.backFaceCulling);
                // Managing instances
                var batch = mesh._getInstancesRenderList(subMesh._id);
                if (batch.mustReturn) {
                    return;
                }
                var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
                if (_this._isReady(subMesh, hardwareInstancedRendering)) {
                    var effect = _this._volumetricLightScatteringPass;
                    if (mesh === _this.mesh) {
                        if (subMesh.effect) {
                            effect = subMesh.effect;
                        }
                        else {
                            effect = material.getEffect();
                        }
                    }
                    engine.enableEffect(effect);
                    mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
                    if (mesh === _this.mesh) {
                        material.bind(mesh.getWorldMatrix(), mesh);
                    }
                    else {
                        _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
                        // Alpha test
                        if (material && material.needAlphaTesting()) {
                            var alphaTexture = material.getAlphaTestTexture();
                            _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
                            if (alphaTexture) {
                                _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                            }
                        }
                        // Bones
                        if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                            _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                        }
                    }
                    // Draw
                    mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
                }
            };
            // Render target texture callbacks
            var savedSceneClearColor;
            var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
            this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
                savedSceneClearColor = scene.clearColor;
                scene.clearColor = sceneClearColor;
            });
            this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
                scene.clearColor = savedSceneClearColor;
            });
            this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
                var engine = scene.getEngine();
                var index;
                if (depthOnlySubMeshes.length) {
                    engine.setColorWrite(false);
                    for (index = 0; index < depthOnlySubMeshes.length; index++) {
                        renderSubMesh(depthOnlySubMeshes.data[index]);
                    }
                    engine.setColorWrite(true);
                }
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    renderSubMesh(alphaTestSubMeshes.data[index]);
                }
                if (transparentSubMeshes.length) {
                    // Sort sub meshes
                    for (index = 0; index < transparentSubMeshes.length; index++) {
                        var submesh = transparentSubMeshes.data[index];
                        var boundingInfo = submesh.getBoundingInfo();
                        if (boundingInfo && scene.activeCamera) {
                            submesh._alphaIndex = submesh.getMesh().alphaIndex;
                            submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
                        }
                    }
                    var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
                    sortedArray.sort(function (a, b) {
                        // Alpha index first
                        if (a._alphaIndex > b._alphaIndex) {
                            return 1;
                        }
                        if (a._alphaIndex < b._alphaIndex) {
                            return -1;
                        }
                        // Then distance to camera
                        if (a._distanceToCamera < b._distanceToCamera) {
                            return 1;
                        }
                        if (a._distanceToCamera > b._distanceToCamera) {
                            return -1;
                        }
                        return 0;
                    });
                    // Render sub meshes
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                    for (index = 0; index < sortedArray.length; index++) {
                        renderSubMesh(sortedArray[index]);
                    }
                    engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
                }
            };
        };
        VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
            var transform = scene.getTransformMatrix();
            var meshPosition;
            if (this.useCustomMeshPosition) {
                meshPosition = this.customMeshPosition;
            }
            else if (this.attachedNode) {
                meshPosition = this.attachedNode.position;
            }
            else {
                meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
            }
            var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
            this._screenCoordinates.x = pos.x / this._viewPort.width;
            this._screenCoordinates.y = pos.y / this._viewPort.height;
            if (this.invert) {
                this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
            }
        };
        // Static methods
        /**
        * Creates a default mesh for the Volumeric Light Scattering post-process
        * @param name The mesh name
        * @param scene The scene where to create the mesh
        * @return the default mesh
        */
        VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
            var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
            mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
            var material = new BABYLON.StandardMaterial(name + "Material", scene);
            material.emissiveColor = new BABYLON.Color3(1, 1, 1);
            mesh.material = material;
            return mesh;
        };
        __decorate([
            BABYLON.serializeAsVector3()
        ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
        __decorate([
            BABYLON.serializeAsMeshReference()
        ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
        __decorate([
            BABYLON.serialize()
        ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
        return VolumetricLightScatteringPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     *
     * This post-process allows the modification of rendered colors by using
     * a 'look-up table' (LUT). This effect is also called Color Grading.
     *
     * The object needs to be provided an url to a texture containing the color
     * look-up table: the texture must be 256 pixels wide and 16 pixels high.
     * Use an image editing software to tweak the LUT to match your needs.
     *
     * For an example of a color LUT, see here:
     * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
     * For explanations on color grading, see here:
     * @see http://udn.epicgames.com/Three/ColorGrading.html
     *
     */
    var ColorCorrectionPostProcess = /** @class */ (function (_super) {
        __extends(ColorCorrectionPostProcess, _super);
        function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
            var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
            _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            _this._colorTableTexture.anisotropicFilteringLevel = 1;
            _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            _this.onApply = function (effect) {
                effect.setTexture("colorTable", _this._colorTableTexture);
            };
            return _this;
        }
        return ColorCorrectionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /** Defines operator used for tonemapping */
    var TonemappingOperator;
    (function (TonemappingOperator) {
        /** Hable */
        TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
        /** Reinhard */
        TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
        /** HejiDawson */
        TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
        /** Photographic */
        TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
    })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
    /**
     * Defines a post process to apply tone mapping
     */
    var TonemapPostProcess = /** @class */ (function (_super) {
        __extends(TonemapPostProcess, _super);
        /**
         * Creates a new TonemapPostProcess
         * @param name defines the name of the postprocess
         * @param _operator defines the operator to use
         * @param exposureAdjustment defines the required exposure adjustement
         * @param camera defines the camera to use (can be null)
         * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
         * @param engine defines the hosting engine (can be ignore if camera is set)
         * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
         */
        function TonemapPostProcess(name, _operator, 
        /** Defines the required exposure adjustement */
        exposureAdjustment, camera, samplingMode, engine, textureFormat) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
            _this._operator = _operator;
            _this.exposureAdjustment = exposureAdjustment;
            var defines = "#define ";
            if (_this._operator === TonemappingOperator.Hable) {
                defines += "HABLE_TONEMAPPING";
            }
            else if (_this._operator === TonemappingOperator.Reinhard) {
                defines += "REINHARD_TONEMAPPING";
            }
            else if (_this._operator === TonemappingOperator.HejiDawson) {
                defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
            }
            else if (_this._operator === TonemappingOperator.Photographic) {
                defines += "PHOTOGRAPHIC_TONEMAPPING";
            }
            //sadly a second call to create the effect.
            _this.updateEffect(defines);
            _this.onApply = function (effect) {
                effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
            };
            return _this;
        }
        return TonemapPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.TonemapPostProcess = TonemapPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.tonemapPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * DisplayPassPostProcess which produces an output the same as it's input
     */
    var DisplayPassPostProcess = /** @class */ (function (_super) {
        __extends(DisplayPassPostProcess, _super);
        /**
         * Creates the DisplayPassPostProcess
         * @param name The name of the effect.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         */
        function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
            return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
        }
        return DisplayPassPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.displayPassPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Extracts highlights from the image
     * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
     */
    var HighlightsPostProcess = /** @class */ (function (_super) {
        __extends(HighlightsPostProcess, _super);
        /**
         * Extracts highlights from the image
         * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
         * @param name The name of the effect.
         * @param options The required width/height ratio to downsize to before computing the render pass.
         * @param camera The camera to apply the render pass to.
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
         */
        function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
        }
        return HighlightsPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.HighlightsPostProcess = HighlightsPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.highlightsPostProcess.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * ImageProcessingPostProcess
     * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
     */
    var ImageProcessingPostProcess = /** @class */ (function (_super) {
        __extends(ImageProcessingPostProcess, _super);
        function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
            if (camera === void 0) { camera = null; }
            if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
            var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
            _this._fromLinearSpace = true;
            /**
             * Defines cache preventing GC.
             */
            _this._defines = {
                IMAGEPROCESSING: false,
                VIGNETTE: false,
                VIGNETTEBLENDMODEMULTIPLY: false,
                VIGNETTEBLENDMODEOPAQUE: false,
                TONEMAPPING: false,
                TONEMAPPING_ACES: false,
                CONTRAST: false,
                COLORCURVES: false,
                COLORGRADING: false,
                COLORGRADING3D: false,
                FROMLINEARSPACE: false,
                SAMPLER3DGREENDEPTH: false,
                SAMPLER3DBGRMAP: false,
                IMAGEPROCESSINGPOSTPROCESS: false,
                EXPOSURE: false,
            };
            // Setup the configuration as forced by the constructor. This would then not force the
            // scene materials output in linear space and let untouched the default forward pass.
            if (imageProcessingConfiguration) {
                imageProcessingConfiguration.applyByPostProcess = true;
                _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
                // This will cause the shader to be compiled
                _this.fromLinearSpace = false;
            }
            // Setup the default processing configuration to the scene.
            else {
                _this._attachImageProcessingConfiguration(null, true);
                _this.imageProcessingConfiguration.applyByPostProcess = true;
            }
            _this.onApply = function (effect) {
                _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
            };
            return _this;
        }
        Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
            /**
             * Gets the image processing configuration used either in this material.
             */
            get: function () {
                return this._imageProcessingConfiguration;
            },
            /**
             * Sets the Default image processing configuration used either in the this material.
             *
             * If sets to null, the scene one is in use.
             */
            set: function (value) {
                this._attachImageProcessingConfiguration(value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attaches a new image processing configuration to the PBR Material.
         * @param configuration
         */
        ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
            var _this = this;
            if (doNotBuild === void 0) { doNotBuild = false; }
            if (configuration === this._imageProcessingConfiguration) {
                return;
            }
            // Detaches observer.
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            // Pick the scene configuration if needed.
            if (!configuration) {
                var scene = null;
                var engine = this.getEngine();
                var camera = this.getCamera();
                if (camera) {
                    scene = camera.getScene();
                }
                else if (engine && engine.scenes) {
                    var scenes = engine.scenes;
                    scene = scenes[scenes.length - 1];
                }
                else {
                    scene = BABYLON.Engine.LastCreatedScene;
                }
                this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
            }
            else {
                this._imageProcessingConfiguration = configuration;
            }
            // Attaches observer.
            if (this._imageProcessingConfiguration) {
                this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
                    _this._updateParameters();
                });
            }
            // Ensure the effect will be rebuilt.
            if (!doNotBuild) {
                this._updateParameters();
            }
        };
        Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
            /**
             * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
             */
            get: function () {
                return this.imageProcessingConfiguration.colorCurves;
            },
            /**
             * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorCurves = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
            /**
             * Gets wether the color curves effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorCurvesEnabled;
            },
            /**
             * Sets wether the color curves effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorCurvesEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
            /**
             * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorGradingTexture;
            },
            /**
             * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorGradingTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
            /**
             * Gets wether the color grading effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorGradingEnabled;
            },
            /**
             * Gets wether the color grading effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorGradingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
            /**
             * Gets exposure used in the effect.
             */
            get: function () {
                return this.imageProcessingConfiguration.exposure;
            },
            /**
             * Sets exposure used in the effect.
             */
            set: function (value) {
                this.imageProcessingConfiguration.exposure = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
            /**
             * Gets wether tonemapping is enabled or not.
             */
            get: function () {
                return this._imageProcessingConfiguration.toneMappingEnabled;
            },
            /**
             * Sets wether tonemapping is enabled or not
             */
            set: function (value) {
                this._imageProcessingConfiguration.toneMappingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
            /**
             * Gets contrast used in the effect.
             */
            get: function () {
                return this.imageProcessingConfiguration.contrast;
            },
            /**
             * Sets contrast used in the effect.
             */
            set: function (value) {
                this.imageProcessingConfiguration.contrast = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
            /**
             * Gets Vignette stretch size.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteStretch;
            },
            /**
             * Sets Vignette stretch size.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteStretch = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
            /**
             * Gets Vignette centre X Offset.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteCentreX;
            },
            /**
             * Sets Vignette centre X Offset.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteCentreX = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
            /**
             * Gets Vignette centre Y Offset.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteCentreY;
            },
            /**
             * Sets Vignette centre Y Offset.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteCentreY = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
            /**
             * Gets Vignette weight or intensity of the vignette effect.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteWeight;
            },
            /**
             * Sets Vignette weight or intensity of the vignette effect.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteWeight = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
            /**
             * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
             * if vignetteEnabled is set to true.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteColor;
            },
            /**
             * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
             * if vignetteEnabled is set to true.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteColor = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
            /**
             * Gets Camera field of view used by the Vignette effect.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteCameraFov;
            },
            /**
             * Sets Camera field of view used by the Vignette effect.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteCameraFov = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
            /**
             * Gets the vignette blend mode allowing different kind of effect.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteBlendMode;
            },
            /**
             * Sets the vignette blend mode allowing different kind of effect.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteBlendMode = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
            /**
             * Gets wether the vignette effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.vignetteEnabled;
            },
            /**
             * Sets wether the vignette effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.vignetteEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
            /**
             * Gets wether the input of the processing is in Gamma or Linear Space.
             */
            get: function () {
                return this._fromLinearSpace;
            },
            /**
             * Sets wether the input of the processing is in Gamma or Linear Space.
             */
            set: function (value) {
                if (this._fromLinearSpace === value) {
                    return;
                }
                this._fromLinearSpace = value;
                this._updateParameters();
            },
            enumerable: true,
            configurable: true
        });
        /**
         *  "ImageProcessingPostProcess"
         * @returns "ImageProcessingPostProcess"
         */
        ImageProcessingPostProcess.prototype.getClassName = function () {
            return "ImageProcessingPostProcess";
        };
        ImageProcessingPostProcess.prototype._updateParameters = function () {
            this._defines.FROMLINEARSPACE = this._fromLinearSpace;
            this.imageProcessingConfiguration.prepareDefines(this._defines, true);
            var defines = "";
            for (var define in this._defines) {
                if (this._defines[define]) {
                    defines += "#define " + define + ";\r\n";
                }
            }
            var samplers = ["textureSampler"];
            var uniforms = ["scale"];
            if (BABYLON.ImageProcessingConfiguration) {
                BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
                BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
            }
            this.updateEffect(defines, uniforms, samplers);
        };
        ImageProcessingPostProcess.prototype.dispose = function (camera) {
            _super.prototype.dispose.call(this, camera);
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            if (this._imageProcessingConfiguration) {
                this.imageProcessingConfiguration.applyByPostProcess = false;
            }
        };
        __decorate([
            BABYLON.serialize()
        ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
        return ImageProcessingPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.imageProcessingPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store bone information
     * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
     */
    var Bone = /** @class */ (function (_super) {
        __extends(Bone, _super);
        /**
         * Create a new bone
         * @param name defines the bone name
         * @param skeleton defines the parent skeleton
         * @param parentBone defines the parent (can be null if the bone is the root)
         * @param localMatrix defines the local matrix
         * @param restPose defines the rest pose matrix
         * @param baseMatrix defines the base matrix
         * @param index defines index of the bone in the hiearchy
         */
        function Bone(
        /**
         * defines the bone name
         */
        name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
            if (parentBone === void 0) { parentBone = null; }
            if (localMatrix === void 0) { localMatrix = null; }
            if (restPose === void 0) { restPose = null; }
            if (baseMatrix === void 0) { baseMatrix = null; }
            if (index === void 0) { index = null; }
            var _this = _super.call(this, name, skeleton.getScene()) || this;
            _this.name = name;
            /**
             * Gets the list of child bones
             */
            _this.children = new Array();
            /** Gets the animations associated with this bone */
            _this.animations = new Array();
            /**
             * @hidden Internal only
             * Set this value to map this bone to a different index in the transform matrices
             * Set this value to -1 to exclude the bone from the transform matrices
             */
            _this._index = null;
            _this._absoluteTransform = new BABYLON.Matrix();
            _this._invertedAbsoluteTransform = new BABYLON.Matrix();
            _this._scalingDeterminant = 1;
            _this._worldTransform = new BABYLON.Matrix();
            _this._needToDecompose = true;
            _this._needToCompose = false;
            _this._skeleton = skeleton;
            _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
            _this._restPose = restPose ? restPose : _this._localMatrix.clone();
            _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
            _this._index = index;
            skeleton.bones.push(_this);
            _this.setParent(parentBone, false);
            if (baseMatrix || localMatrix) {
                _this._updateDifferenceMatrix();
            }
            return _this;
        }
        Object.defineProperty(Bone.prototype, "_matrix", {
            /** @hidden */
            get: function () {
                this._compose();
                return this._localMatrix;
            },
            /** @hidden */
            set: function (value) {
                this._localMatrix.copyFrom(value);
                this._needToDecompose = true;
            },
            enumerable: true,
            configurable: true
        });
        // Members
        /**
         * Gets the parent skeleton
         * @returns a skeleton
         */
        Bone.prototype.getSkeleton = function () {
            return this._skeleton;
        };
        /**
         * Gets parent bone
         * @returns a bone or null if the bone is the root of the bone hierarchy
         */
        Bone.prototype.getParent = function () {
            return this._parent;
        };
        /**
         * Sets the parent bone
         * @param parent defines the parent (can be null if the bone is the root)
         * @param updateDifferenceMatrix defines if the difference matrix must be updated
         */
        Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
            if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
            if (this._parent === parent) {
                return;
            }
            if (this._parent) {
                var index = this._parent.children.indexOf(this);
                if (index !== -1) {
                    this._parent.children.splice(index, 1);
                }
            }
            this._parent = parent;
            if (this._parent) {
                this._parent.children.push(this);
            }
            if (updateDifferenceMatrix) {
                this._updateDifferenceMatrix();
            }
            this.markAsDirty();
        };
        /**
         * Gets the local matrix
         * @returns a matrix
         */
        Bone.prototype.getLocalMatrix = function () {
            this._compose();
            return this._localMatrix;
        };
        /**
         * Gets the base matrix (initial matrix which remains unchanged)
         * @returns a matrix
         */
        Bone.prototype.getBaseMatrix = function () {
            return this._baseMatrix;
        };
        /**
         * Gets the rest pose matrix
         * @returns a matrix
         */
        Bone.prototype.getRestPose = function () {
            return this._restPose;
        };
        /**
         * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
         */
        Bone.prototype.getWorldMatrix = function () {
            return this._worldTransform;
        };
        /**
         * Sets the local matrix to rest pose matrix
         */
        Bone.prototype.returnToRest = function () {
            this.updateMatrix(this._restPose.clone());
        };
        /**
         * Gets the inverse of the absolute transform matrix.
         * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
         * @returns a matrix
         */
        Bone.prototype.getInvertedAbsoluteTransform = function () {
            return this._invertedAbsoluteTransform;
        };
        /**
         * Gets the absolute transform matrix (ie base matrix * parent world matrix)
         * @returns a matrix
         */
        Bone.prototype.getAbsoluteTransform = function () {
            return this._absoluteTransform;
        };
        Object.defineProperty(Bone.prototype, "position", {
            // Properties (matches AbstractMesh properties)
            /** Gets or sets current position (in local space) */
            get: function () {
                this._decompose();
                return this._localPosition;
            },
            set: function (newPosition) {
                this._decompose();
                this._localPosition.copyFrom(newPosition);
                this._markAsDirtyAndCompose();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bone.prototype, "rotation", {
            /** Gets or sets current rotation (in local space) */
            get: function () {
                return this.getRotation();
            },
            set: function (newRotation) {
                this.setRotation(newRotation);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bone.prototype, "rotationQuaternion", {
            /** Gets or sets current rotation quaternion (in local space) */
            get: function () {
                this._decompose();
                return this._localRotation;
            },
            set: function (newRotation) {
                this.setRotationQuaternion(newRotation);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bone.prototype, "scaling", {
            /** Gets or sets current scaling (in local space) */
            get: function () {
                return this.getScale();
            },
            set: function (newScaling) {
                this.setScale(newScaling);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
            /**
             * Gets the animation properties override
             */
            get: function () {
                return this._skeleton.animationPropertiesOverride;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        Bone.prototype._decompose = function () {
            if (!this._needToDecompose) {
                return;
            }
            this._needToDecompose = false;
            if (!this._localScaling) {
                this._localScaling = BABYLON.Vector3.Zero();
                this._localRotation = BABYLON.Quaternion.Zero();
                this._localPosition = BABYLON.Vector3.Zero();
            }
            this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
        };
        Bone.prototype._compose = function () {
            if (!this._needToCompose) {
                return;
            }
            this._needToCompose = false;
            BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
        };
        /**
         * Update the base and local matrices
         * @param matrix defines the new base or local matrix
         * @param updateDifferenceMatrix defines if the difference matrix must be updated
         * @param updateLocalMatrix defines if the local matrix should be updated
         */
        Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
            if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
            if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
            this._baseMatrix.copyFrom(matrix);
            if (updateDifferenceMatrix) {
                this._updateDifferenceMatrix();
            }
            if (updateLocalMatrix) {
                this._localMatrix.copyFrom(matrix);
                this._markAsDirtyAndDecompose();
            }
            else {
                this.markAsDirty();
            }
        };
        /** @hidden */
        Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
            if (updateChildren === void 0) { updateChildren = true; }
            if (!rootMatrix) {
                rootMatrix = this._baseMatrix;
            }
            if (this._parent) {
                rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
            }
            else {
                this._absoluteTransform.copyFrom(rootMatrix);
            }
            this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
            if (updateChildren) {
                for (var index = 0; index < this.children.length; index++) {
                    this.children[index]._updateDifferenceMatrix();
                }
            }
            this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
        };
        /**
         * Flag the bone as dirty (Forcing it to update everything)
         */
        Bone.prototype.markAsDirty = function () {
            this._currentRenderId++;
            this._childRenderId++;
            this._skeleton._markAsDirty();
        };
        Bone.prototype._markAsDirtyAndCompose = function () {
            this.markAsDirty();
            this._needToCompose = true;
        };
        Bone.prototype._markAsDirtyAndDecompose = function () {
            this.markAsDirty();
            this._needToDecompose = true;
        };
        /**
         * Copy an animation range from another bone
         * @param source defines the source bone
         * @param rangeName defines the range name to copy
         * @param frameOffset defines the frame offset
         * @param rescaleAsRequired defines if rescaling must be applied if required
         * @param skelDimensionsRatio defines the scaling ratio
         * @returns true if operation was successful
         */
        Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
            if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
            // all animation may be coming from a library skeleton, so may need to create animation
            if (this.animations.length === 0) {
                this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
                this.animations[0].setKeys([]);
            }
            // get animation info / verify there is such a range from the source bone
            var sourceRange = source.animations[0].getRange(rangeName);
            if (!sourceRange) {
                return false;
            }
            var from = sourceRange.from;
            var to = sourceRange.to;
            var sourceKeys = source.animations[0].getKeys();
            // rescaling prep
            var sourceBoneLength = source.length;
            var sourceParent = source.getParent();
            var parent = this.getParent();
            var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
            var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
            var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
            var destKeys = this.animations[0].getKeys();
            // loop vars declaration
            var orig;
            var origTranslation;
            var mat;
            for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
                orig = sourceKeys[key];
                if (orig.frame >= from && orig.frame <= to) {
                    if (rescaleAsRequired) {
                        mat = orig.value.clone();
                        // scale based on parent ratio, when bone has parent
                        if (parentScalingReqd) {
                            origTranslation = mat.getTranslation();
                            mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
                            // scale based on skeleton dimension ratio when root bone, and value is passed
                        }
                        else if (dimensionsScalingReqd && skelDimensionsRatio) {
                            origTranslation = mat.getTranslation();
                            mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
                            // use original when root bone, and no data for skelDimensionsRatio
                        }
                        else {
                            mat = orig.value;
                        }
                    }
                    else {
                        mat = orig.value;
                    }
                    destKeys.push({ frame: orig.frame + frameOffset, value: mat });
                }
            }
            this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
            return true;
        };
        /**
         * Translate the bone in local or world space
         * @param vec The amount to translate the bone
         * @param space The space that the translation is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         */
        Bone.prototype.translate = function (vec, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var lm = this.getLocalMatrix();
            if (space == BABYLON.Space.LOCAL) {
                lm.m[12] += vec.x;
                lm.m[13] += vec.y;
                lm.m[14] += vec.z;
            }
            else {
                var wm = null;
                //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
                if (mesh) {
                    wm = mesh.getWorldMatrix();
                }
                this._skeleton.computeAbsoluteTransforms();
                var tmat = Bone._tmpMats[0];
                var tvec = Bone._tmpVecs[0];
                if (this._parent) {
                    if (mesh && wm) {
                        tmat.copyFrom(this._parent.getAbsoluteTransform());
                        tmat.multiplyToRef(wm, tmat);
                    }
                    else {
                        tmat.copyFrom(this._parent.getAbsoluteTransform());
                    }
                }
                tmat.m[12] = 0;
                tmat.m[13] = 0;
                tmat.m[14] = 0;
                tmat.invert();
                BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
                lm.m[12] += tvec.x;
                lm.m[13] += tvec.y;
                lm.m[14] += tvec.z;
            }
            this._markAsDirtyAndDecompose();
        };
        /**
         * Set the postion of the bone in local or world space
         * @param position The position to set the bone
         * @param space The space that the position is in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         */
        Bone.prototype.setPosition = function (position, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var lm = this.getLocalMatrix();
            if (space == BABYLON.Space.LOCAL) {
                lm.m[12] = position.x;
                lm.m[13] = position.y;
                lm.m[14] = position.z;
            }
            else {
                var wm = null;
                //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
                if (mesh) {
                    wm = mesh.getWorldMatrix();
                }
                this._skeleton.computeAbsoluteTransforms();
                var tmat = Bone._tmpMats[0];
                var vec = Bone._tmpVecs[0];
                if (this._parent) {
                    if (mesh && wm) {
                        tmat.copyFrom(this._parent.getAbsoluteTransform());
                        tmat.multiplyToRef(wm, tmat);
                    }
                    else {
                        tmat.copyFrom(this._parent.getAbsoluteTransform());
                    }
                }
                tmat.invert();
                BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
                lm.m[12] = vec.x;
                lm.m[13] = vec.y;
                lm.m[14] = vec.z;
            }
            this._markAsDirtyAndDecompose();
        };
        /**
         * Set the absolute position of the bone (world space)
         * @param position The position to set the bone
         * @param mesh The mesh that this bone is attached to
         */
        Bone.prototype.setAbsolutePosition = function (position, mesh) {
            this.setPosition(position, BABYLON.Space.WORLD, mesh);
        };
        /**
         * Scale the bone on the x, y and z axes (in local space)
         * @param x The amount to scale the bone on the x axis
         * @param y The amount to scale the bone on the y axis
         * @param z The amount to scale the bone on the z axis
         * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
         */
        Bone.prototype.scale = function (x, y, z, scaleChildren) {
            if (scaleChildren === void 0) { scaleChildren = false; }
            var locMat = this.getLocalMatrix();
            // Apply new scaling on top of current local matrix
            var scaleMat = Bone._tmpMats[0];
            BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
            scaleMat.multiplyToRef(locMat, locMat);
            // Invert scaling matrix and apply the inverse to all children
            scaleMat.invert();
            for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
                var child = _a[_i];
                var cm = child.getLocalMatrix();
                cm.multiplyToRef(scaleMat, cm);
                cm.m[12] *= x;
                cm.m[13] *= y;
                cm.m[14] *= z;
                child._markAsDirtyAndDecompose();
            }
            this._markAsDirtyAndDecompose();
            if (scaleChildren) {
                for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
                    var child = _c[_b];
                    child.scale(x, y, z, scaleChildren);
                }
            }
        };
        /**
         * Set the bone scaling in local space
         * @param scale defines the scaling vector
         */
        Bone.prototype.setScale = function (scale) {
            this._decompose();
            this._localScaling.copyFrom(scale);
            this._markAsDirtyAndCompose();
        };
        /**
         * Gets the current scaling in local space
         * @returns the current scaling vector
         */
        Bone.prototype.getScale = function () {
            this._decompose();
            return this._localScaling;
        };
        /**
         * Gets the current scaling in local space and stores it in a target vector
         * @param result defines the target vector
         */
        Bone.prototype.getScaleToRef = function (result) {
            this._decompose();
            result.copyFrom(this._localScaling);
        };
        /**
         * Set the yaw, pitch, and roll of the bone in local or world space
         * @param yaw The rotation of the bone on the y axis
         * @param pitch The rotation of the bone on the x axis
         * @param roll The rotation of the bone on the z axis
         * @param space The space that the axes of rotation are in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         */
        Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space === BABYLON.Space.LOCAL) {
                var quat = Bone._tmpQuat;
                BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
                this.setRotationQuaternion(quat, space, mesh);
                return;
            }
            var rotMatInv = Bone._tmpMats[0];
            if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
                return;
            }
            var rotMat = Bone._tmpMats[1];
            BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
            rotMatInv.multiplyToRef(rotMat, rotMat);
            this._rotateWithMatrix(rotMat, space, mesh);
        };
        /**
         * Add a rotation to the bone on an axis in local or world space
         * @param axis The axis to rotate the bone on
         * @param amount The amount to rotate the bone
         * @param space The space that the axis is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         */
        Bone.prototype.rotate = function (axis, amount, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var rmat = Bone._tmpMats[0];
            rmat.m[12] = 0;
            rmat.m[13] = 0;
            rmat.m[14] = 0;
            BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
            this._rotateWithMatrix(rmat, space, mesh);
        };
        /**
         * Set the rotation of the bone to a particular axis angle in local or world space
         * @param axis The axis to rotate the bone on
         * @param angle The angle that the bone should be rotated to
         * @param space The space that the axis is in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         */
        Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space === BABYLON.Space.LOCAL) {
                var quat = Bone._tmpQuat;
                BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
                this.setRotationQuaternion(quat, space, mesh);
                return;
            }
            var rotMatInv = Bone._tmpMats[0];
            if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
                return;
            }
            var rotMat = Bone._tmpMats[1];
            BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
            rotMatInv.multiplyToRef(rotMat, rotMat);
            this._rotateWithMatrix(rotMat, space, mesh);
        };
        /**
         * Set the euler rotation of the bone in local of world space
         * @param rotation The euler rotation that the bone should be set to
         * @param space The space that the rotation is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         */
        Bone.prototype.setRotation = function (rotation, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
        };
        /**
         * Set the quaternion rotation of the bone in local of world space
         * @param quat The quaternion rotation that the bone should be set to
         * @param space The space that the rotation is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         */
        Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space === BABYLON.Space.LOCAL) {
                this._decompose();
                this._localRotation.copyFrom(quat);
                this._markAsDirtyAndCompose();
                return;
            }
            var rotMatInv = Bone._tmpMats[0];
            if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
                return;
            }
            var rotMat = Bone._tmpMats[1];
            BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
            rotMatInv.multiplyToRef(rotMat, rotMat);
            this._rotateWithMatrix(rotMat, space, mesh);
        };
        /**
         * Set the rotation matrix of the bone in local of world space
         * @param rotMat The rotation matrix that the bone should be set to
         * @param space The space that the rotation is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         */
        Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space === BABYLON.Space.LOCAL) {
                var quat = Bone._tmpQuat;
                BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
                this.setRotationQuaternion(quat, space, mesh);
                return;
            }
            var rotMatInv = Bone._tmpMats[0];
            if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
                return;
            }
            var rotMat2 = Bone._tmpMats[1];
            rotMat2.copyFrom(rotMat);
            rotMatInv.multiplyToRef(rotMat, rotMat2);
            this._rotateWithMatrix(rotMat2, space, mesh);
        };
        Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var lmat = this.getLocalMatrix();
            var lx = lmat.m[12];
            var ly = lmat.m[13];
            var lz = lmat.m[14];
            var parent = this.getParent();
            var parentScale = Bone._tmpMats[3];
            var parentScaleInv = Bone._tmpMats[4];
            if (parent && space == BABYLON.Space.WORLD) {
                if (mesh) {
                    parentScale.copyFrom(mesh.getWorldMatrix());
                    parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
                }
                else {
                    parentScale.copyFrom(parent.getAbsoluteTransform());
                }
                parentScaleInv.copyFrom(parentScale);
                parentScaleInv.invert();
                lmat.multiplyToRef(parentScale, lmat);
                lmat.multiplyToRef(rmat, lmat);
                lmat.multiplyToRef(parentScaleInv, lmat);
            }
            else {
                if (space == BABYLON.Space.WORLD && mesh) {
                    parentScale.copyFrom(mesh.getWorldMatrix());
                    parentScaleInv.copyFrom(parentScale);
                    parentScaleInv.invert();
                    lmat.multiplyToRef(parentScale, lmat);
                    lmat.multiplyToRef(rmat, lmat);
                    lmat.multiplyToRef(parentScaleInv, lmat);
                }
                else {
                    lmat.multiplyToRef(rmat, lmat);
                }
            }
            lmat.m[12] = lx;
            lmat.m[13] = ly;
            lmat.m[14] = lz;
            this.computeAbsoluteTransforms();
            this._markAsDirtyAndDecompose();
        };
        Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
            var scaleMatrix = Bone._tmpMats[2];
            rotMatInv.copyFrom(this.getAbsoluteTransform());
            if (mesh) {
                rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
                BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
            }
            rotMatInv.invert();
            if (isNaN(rotMatInv.m[0])) {
                // Matrix failed to invert.
                // This can happen if scale is zero for example.
                return false;
            }
            scaleMatrix.m[0] *= this._scalingDeterminant;
            rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
            return true;
        };
        /**
         * Get the position of the bone in local or world space
         * @param space The space that the returned position is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         * @returns The position of the bone
         */
        Bone.prototype.getPosition = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (mesh === void 0) { mesh = null; }
            var pos = BABYLON.Vector3.Zero();
            this.getPositionToRef(space, mesh, pos);
            return pos;
        };
        /**
         * Copy the position of the bone to a vector3 in local or world space
         * @param space The space that the returned position is in
         * @param mesh The mesh that this bone is attached to. This is only used in world space
         * @param result The vector3 to copy the position to
         */
        Bone.prototype.getPositionToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space == BABYLON.Space.LOCAL) {
                var lm = this.getLocalMatrix();
                result.x = lm.m[12];
                result.y = lm.m[13];
                result.z = lm.m[14];
            }
            else {
                var wm = null;
                //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
                if (mesh) {
                    wm = mesh.getWorldMatrix();
                }
                this._skeleton.computeAbsoluteTransforms();
                var tmat = Bone._tmpMats[0];
                if (mesh && wm) {
                    tmat.copyFrom(this.getAbsoluteTransform());
                    tmat.multiplyToRef(wm, tmat);
                }
                else {
                    tmat = this.getAbsoluteTransform();
                }
                result.x = tmat.m[12];
                result.y = tmat.m[13];
                result.z = tmat.m[14];
            }
        };
        /**
         * Get the absolute position of the bone (world space)
         * @param mesh The mesh that this bone is attached to
         * @returns The absolute position of the bone
         */
        Bone.prototype.getAbsolutePosition = function (mesh) {
            if (mesh === void 0) { mesh = null; }
            var pos = BABYLON.Vector3.Zero();
            this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
            return pos;
        };
        /**
         * Copy the absolute position of the bone (world space) to the result param
         * @param mesh The mesh that this bone is attached to
         * @param result The vector3 to copy the absolute position to
         */
        Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
            this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
        };
        /**
         * Compute the absolute transforms of this bone and its children
         */
        Bone.prototype.computeAbsoluteTransforms = function () {
            this._compose();
            if (this._parent) {
                this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
            }
            else {
                this._absoluteTransform.copyFrom(this._localMatrix);
                var poseMatrix = this._skeleton.getPoseMatrix();
                if (poseMatrix) {
                    this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
                }
            }
            var children = this.children;
            var len = children.length;
            for (var i = 0; i < len; i++) {
                children[i].computeAbsoluteTransforms();
            }
        };
        /**
         * Get the world direction from an axis that is in the local space of the bone
         * @param localAxis The local direction that is used to compute the world direction
         * @param mesh The mesh that this bone is attached to
         * @returns The world direction
         */
        Bone.prototype.getDirection = function (localAxis, mesh) {
            if (mesh === void 0) { mesh = null; }
            var result = BABYLON.Vector3.Zero();
            this.getDirectionToRef(localAxis, mesh, result);
            return result;
        };
        /**
         * Copy the world direction to a vector3 from an axis that is in the local space of the bone
         * @param localAxis The local direction that is used to compute the world direction
         * @param mesh The mesh that this bone is attached to
         * @param result The vector3 that the world direction will be copied to
         */
        Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
            if (mesh === void 0) { mesh = null; }
            var wm = null;
            //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
            if (mesh) {
                wm = mesh.getWorldMatrix();
            }
            this._skeleton.computeAbsoluteTransforms();
            var mat = Bone._tmpMats[0];
            mat.copyFrom(this.getAbsoluteTransform());
            if (mesh && wm) {
                mat.multiplyToRef(wm, mat);
            }
            BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
            result.normalize();
        };
        /**
         * Get the euler rotation of the bone in local or world space
         * @param space The space that the rotation should be in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         * @returns The euler rotation
         */
        Bone.prototype.getRotation = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (mesh === void 0) { mesh = null; }
            var result = BABYLON.Vector3.Zero();
            this.getRotationToRef(space, mesh, result);
            return result;
        };
        /**
         * Copy the euler rotation of the bone to a vector3.  The rotation can be in either local or world space
         * @param space The space that the rotation should be in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         * @param result The vector3 that the rotation should be copied to
         */
        Bone.prototype.getRotationToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (mesh === void 0) { mesh = null; }
            var quat = Bone._tmpQuat;
            this.getRotationQuaternionToRef(space, mesh, quat);
            quat.toEulerAnglesToRef(result);
        };
        /**
         * Get the quaternion rotation of the bone in either local or world space
         * @param space The space that the rotation should be in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         * @returns The quaternion rotation
         */
        Bone.prototype.getRotationQuaternion = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (mesh === void 0) { mesh = null; }
            var result = BABYLON.Quaternion.Identity();
            this.getRotationQuaternionToRef(space, mesh, result);
            return result;
        };
        /**
         * Copy the quaternion rotation of the bone to a quaternion.  The rotation can be in either local or world space
         * @param space The space that the rotation should be in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         * @param result The quaternion that the rotation should be copied to
         */
        Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (mesh === void 0) { mesh = null; }
            if (space == BABYLON.Space.LOCAL) {
                this._decompose();
                result.copyFrom(this._localRotation);
            }
            else {
                var mat = Bone._tmpMats[0];
                var amat = this.getAbsoluteTransform();
                if (mesh) {
                    amat.multiplyToRef(mesh.getWorldMatrix(), mat);
                }
                else {
                    mat.copyFrom(amat);
                }
                mat.m[0] *= this._scalingDeterminant;
                mat.m[1] *= this._scalingDeterminant;
                mat.m[2] *= this._scalingDeterminant;
                mat.decompose(undefined, result, undefined);
            }
        };
        /**
         * Get the rotation matrix of the bone in local or world space
         * @param space The space that the rotation should be in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         * @returns The rotation matrix
         */
        Bone.prototype.getRotationMatrix = function (space, mesh) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            var result = BABYLON.Matrix.Identity();
            this.getRotationMatrixToRef(space, mesh, result);
            return result;
        };
        /**
         * Copy the rotation matrix of the bone to a matrix.  The rotation can be in either local or world space
         * @param space The space that the rotation should be in
         * @param mesh The mesh that this bone is attached to.  This is only used in world space
         * @param result The quaternion that the rotation should be copied to
         */
        Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
            if (space === void 0) { space = BABYLON.Space.LOCAL; }
            if (space == BABYLON.Space.LOCAL) {
                this.getLocalMatrix().getRotationMatrixToRef(result);
            }
            else {
                var mat = Bone._tmpMats[0];
                var amat = this.getAbsoluteTransform();
                if (mesh) {
                    amat.multiplyToRef(mesh.getWorldMatrix(), mat);
                }
                else {
                    mat.copyFrom(amat);
                }
                mat.m[0] *= this._scalingDeterminant;
                mat.m[1] *= this._scalingDeterminant;
                mat.m[2] *= this._scalingDeterminant;
                mat.getRotationMatrixToRef(result);
            }
        };
        /**
         * Get the world position of a point that is in the local space of the bone
         * @param position The local position
         * @param mesh The mesh that this bone is attached to
         * @returns The world position
         */
        Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
            if (mesh === void 0) { mesh = null; }
            var result = BABYLON.Vector3.Zero();
            this.getAbsolutePositionFromLocalToRef(position, mesh, result);
            return result;
        };
        /**
         * Get the world position of a point that is in the local space of the bone and copy it to the result param
         * @param position The local position
         * @param mesh The mesh that this bone is attached to
         * @param result The vector3 that the world position should be copied to
         */
        Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
            if (mesh === void 0) { mesh = null; }
            var wm = null;
            //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
            if (mesh) {
                wm = mesh.getWorldMatrix();
            }
            this._skeleton.computeAbsoluteTransforms();
            var tmat = Bone._tmpMats[0];
            if (mesh && wm) {
                tmat.copyFrom(this.getAbsoluteTransform());
                tmat.multiplyToRef(wm, tmat);
            }
            else {
                tmat = this.getAbsoluteTransform();
            }
            BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
        };
        /**
         * Get the local position of a point that is in world space
         * @param position The world position
         * @param mesh The mesh that this bone is attached to
         * @returns The local position
         */
        Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
            if (mesh === void 0) { mesh = null; }
            var result = BABYLON.Vector3.Zero();
            this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
            return result;
        };
        /**
         * Get the local position of a point that is in world space and copy it to the result param
         * @param position The world position
         * @param mesh The mesh that this bone is attached to
         * @param result The vector3 that the local position should be copied to
         */
        Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
            if (mesh === void 0) { mesh = null; }
            var wm = null;
            //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
            if (mesh) {
                wm = mesh.getWorldMatrix();
            }
            this._skeleton.computeAbsoluteTransforms();
            var tmat = Bone._tmpMats[0];
            tmat.copyFrom(this.getAbsoluteTransform());
            if (mesh && wm) {
                tmat.multiplyToRef(wm, tmat);
            }
            tmat.invert();
            BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
        };
        Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
        Bone._tmpQuat = BABYLON.Quaternion.Identity();
        Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
        return Bone;
    }(BABYLON.Node));
    BABYLON.Bone = Bone;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.bone.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to apply inverse kinematics to bones
     * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
     */
    var BoneIKController = /** @class */ (function () {
        /**
         * Creates a new BoneIKController
         * @param mesh defines the mesh to control
         * @param bone defines the bone to control
         * @param options defines options to set up the controller
         */
        function BoneIKController(mesh, bone, options) {
            /**
             * Gets or sets the target position
             */
            this.targetPosition = BABYLON.Vector3.Zero();
            /**
             * Gets or sets the pole target position
             */
            this.poleTargetPosition = BABYLON.Vector3.Zero();
            /**
             * Gets or sets the pole target local offset
             */
            this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
            /**
             * Gets or sets the pole angle
             */
            this.poleAngle = 0;
            /**
             * The amount to slerp (spherical linear interpolation) to the target.  Set this to a value between 0 and 1 (a value of 1 disables slerp)
             */
            this.slerpAmount = 1;
            this._bone1Quat = BABYLON.Quaternion.Identity();
            this._bone1Mat = BABYLON.Matrix.Identity();
            this._bone2Ang = Math.PI;
            this._maxAngle = Math.PI;
            this._rightHandedSystem = false;
            this._bendAxis = BABYLON.Vector3.Right();
            this._slerping = false;
            this._adjustRoll = 0;
            this._bone2 = bone;
            this._bone1 = bone.getParent();
            if (!this._bone1) {
                return;
            }
            this.mesh = mesh;
            var bonePos = bone.getPosition();
            if (bone.getAbsoluteTransform().determinant() > 0) {
                this._rightHandedSystem = true;
                this._bendAxis.x = 0;
                this._bendAxis.y = 0;
                this._bendAxis.z = -1;
                if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
                    this._adjustRoll = Math.PI * .5;
                    this._bendAxis.z = 1;
                }
            }
            if (this._bone1.length) {
                var boneScale1 = this._bone1.getScale();
                var boneScale2 = this._bone2.getScale();
                this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
                this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
            }
            else if (this._bone1.children[0]) {
                mesh.computeWorldMatrix(true);
                var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
                var pos2 = this._bone2.getAbsolutePosition(mesh);
                var pos3 = this._bone1.getAbsolutePosition(mesh);
                this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
                this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
            }
            this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
            this.maxAngle = Math.PI;
            if (options) {
                if (options.targetMesh) {
                    this.targetMesh = options.targetMesh;
                    this.targetMesh.computeWorldMatrix(true);
                }
                if (options.poleTargetMesh) {
                    this.poleTargetMesh = options.poleTargetMesh;
                    this.poleTargetMesh.computeWorldMatrix(true);
                }
                else if (options.poleTargetBone) {
                    this.poleTargetBone = options.poleTargetBone;
                }
                else if (this._bone1.getParent()) {
                    this.poleTargetBone = this._bone1.getParent();
                }
                if (options.poleTargetLocalOffset) {
                    this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
                }
                if (options.poleAngle) {
                    this.poleAngle = options.poleAngle;
                }
                if (options.bendAxis) {
                    this._bendAxis.copyFrom(options.bendAxis);
                }
                if (options.maxAngle) {
                    this.maxAngle = options.maxAngle;
                }
                if (options.slerpAmount) {
                    this.slerpAmount = options.slerpAmount;
                }
            }
        }
        Object.defineProperty(BoneIKController.prototype, "maxAngle", {
            /**
             * Gets or sets maximum allowed angle
             */
            get: function () {
                return this._maxAngle;
            },
            set: function (value) {
                this._setMaxAngle(value);
            },
            enumerable: true,
            configurable: true
        });
        BoneIKController.prototype._setMaxAngle = function (ang) {
            if (ang < 0) {
                ang = 0;
            }
            if (ang > Math.PI || ang == undefined) {
                ang = Math.PI;
            }
            this._maxAngle = ang;
            var a = this._bone1Length;
            var b = this._bone2Length;
            this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
        };
        /**
         * Force the controller to update the bones
         */
        BoneIKController.prototype.update = function () {
            var bone1 = this._bone1;
            if (!bone1) {
                return;
            }
            var target = this.targetPosition;
            var poleTarget = this.poleTargetPosition;
            var mat1 = BoneIKController._tmpMats[0];
            var mat2 = BoneIKController._tmpMats[1];
            if (this.targetMesh) {
                target.copyFrom(this.targetMesh.getAbsolutePosition());
            }
            if (this.poleTargetBone) {
                this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
            }
            else if (this.poleTargetMesh) {
                BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
            }
            var bonePos = BoneIKController._tmpVecs[0];
            var zaxis = BoneIKController._tmpVecs[1];
            var xaxis = BoneIKController._tmpVecs[2];
            var yaxis = BoneIKController._tmpVecs[3];
            var upAxis = BoneIKController._tmpVecs[4];
            var _tmpQuat = BoneIKController._tmpQuat;
            bone1.getAbsolutePositionToRef(this.mesh, bonePos);
            poleTarget.subtractToRef(bonePos, upAxis);
            if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
                upAxis.y = 1;
            }
            else {
                upAxis.normalize();
            }
            target.subtractToRef(bonePos, yaxis);
            yaxis.normalize();
            BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
            zaxis.normalize();
            BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
            xaxis.normalize();
            BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
            var a = this._bone1Length;
            var b = this._bone2Length;
            var c = BABYLON.Vector3.Distance(bonePos, target);
            if (this._maxReach > 0) {
                c = Math.min(this._maxReach, c);
            }
            var acosa = (b * b + c * c - a * a) / (2 * b * c);
            var acosb = (c * c + a * a - b * b) / (2 * c * a);
            if (acosa > 1) {
                acosa = 1;
            }
            if (acosb > 1) {
                acosb = 1;
            }
            if (acosa < -1) {
                acosa = -1;
            }
            if (acosb < -1) {
                acosb = -1;
            }
            var angA = Math.acos(acosa);
            var angB = Math.acos(acosb);
            var angC = -angA - angB;
            if (this._rightHandedSystem) {
                BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
                mat2.multiplyToRef(mat1, mat1);
                BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
                mat2.multiplyToRef(mat1, mat1);
            }
            else {
                var _tmpVec = BoneIKController._tmpVecs[5];
                _tmpVec.copyFrom(this._bendAxis);
                _tmpVec.x *= -1;
                BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
                mat2.multiplyToRef(mat1, mat1);
            }
            if (this.poleAngle) {
                BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
                mat1.multiplyToRef(mat2, mat1);
            }
            if (this._bone1) {
                if (this.slerpAmount < 1) {
                    if (!this._slerping) {
                        BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
                    }
                    BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
                    BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
                    angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
                    this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
                    this._slerping = true;
                }
                else {
                    this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
                    this._bone1Mat.copyFrom(mat1);
                    this._slerping = false;
                }
            }
            this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
            this._bone2Ang = angC;
        };
        BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
        BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
        BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
        return BoneIKController;
    }());
    BABYLON.BoneIKController = BoneIKController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boneIKController.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to make a bone look toward a point in space
     * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
     */
    var BoneLookController = /** @class */ (function () {
        /**
         * Create a BoneLookController
         * @param mesh the mesh that the bone belongs to
         * @param bone the bone that will be looking to the target
         * @param target the target Vector3 to look at
         * @param settings optional settings:
         * * maxYaw: the maximum angle the bone will yaw to
         * * minYaw: the minimum angle the bone will yaw to
         * * maxPitch: the maximum angle the bone will pitch to
         * * minPitch: the minimum angle the bone will yaw to
         * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
         * * upAxis: the up axis of the coordinate system
         * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
         * * yawAxis: set yawAxis if the bone does not yaw on the y axis
         * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
         * * adjustYaw: used to make an adjustment to the yaw of the bone
         * * adjustPitch: used to make an adjustment to the pitch of the bone
         * * adjustRoll: used to make an adjustment to the roll of the bone
         **/
        function BoneLookController(mesh, bone, target, options) {
            /**
             * The up axis of the coordinate system that is used when the bone is rotated
             */
            this.upAxis = BABYLON.Vector3.Up();
            /**
             * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
             */
            this.upAxisSpace = BABYLON.Space.LOCAL;
            /**
             * Used to make an adjustment to the yaw of the bone
             */
            this.adjustYaw = 0;
            /**
             * Used to make an adjustment to the pitch of the bone
             */
            this.adjustPitch = 0;
            /**
             * Used to make an adjustment to the roll of the bone
             */
            this.adjustRoll = 0;
            /**
             * The amount to slerp (spherical linear interpolation) to the target.  Set this to a value between 0 and 1 (a value of 1 disables slerp)
             */
            this.slerpAmount = 1;
            this._boneQuat = BABYLON.Quaternion.Identity();
            this._slerping = false;
            this._firstFrameSkipped = false;
            this._fowardAxis = BABYLON.Vector3.Forward();
            this.mesh = mesh;
            this.bone = bone;
            this.target = target;
            if (options) {
                if (options.adjustYaw) {
                    this.adjustYaw = options.adjustYaw;
                }
                if (options.adjustPitch) {
                    this.adjustPitch = options.adjustPitch;
                }
                if (options.adjustRoll) {
                    this.adjustRoll = options.adjustRoll;
                }
                if (options.maxYaw != null) {
                    this.maxYaw = options.maxYaw;
                }
                else {
                    this.maxYaw = Math.PI;
                }
                if (options.minYaw != null) {
                    this.minYaw = options.minYaw;
                }
                else {
                    this.minYaw = -Math.PI;
                }
                if (options.maxPitch != null) {
                    this.maxPitch = options.maxPitch;
                }
                else {
                    this.maxPitch = Math.PI;
                }
                if (options.minPitch != null) {
                    this.minPitch = options.minPitch;
                }
                else {
                    this.minPitch = -Math.PI;
                }
                if (options.slerpAmount != null) {
                    this.slerpAmount = options.slerpAmount;
                }
                if (options.upAxis != null) {
                    this.upAxis = options.upAxis;
                }
                if (options.upAxisSpace != null) {
                    this.upAxisSpace = options.upAxisSpace;
                }
                if (options.yawAxis != null || options.pitchAxis != null) {
                    var newYawAxis = BABYLON.Axis.Y;
                    var newPitchAxis = BABYLON.Axis.X;
                    if (options.yawAxis != null) {
                        newYawAxis = options.yawAxis.clone();
                        newYawAxis.normalize();
                    }
                    if (options.pitchAxis != null) {
                        newPitchAxis = options.pitchAxis.clone();
                        newPitchAxis.normalize();
                    }
                    var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
                    this._transformYawPitch = BABYLON.Matrix.Identity();
                    BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
                    this._transformYawPitchInv = this._transformYawPitch.clone();
                    this._transformYawPitch.invert();
                }
            }
            if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
                this.upAxisSpace = BABYLON.Space.LOCAL;
            }
        }
        Object.defineProperty(BoneLookController.prototype, "minYaw", {
            /**
             * Gets or sets the minimum yaw angle that the bone can look to
             */
            get: function () {
                return this._minYaw;
            },
            set: function (value) {
                this._minYaw = value;
                this._minYawSin = Math.sin(value);
                this._minYawCos = Math.cos(value);
                if (this._maxYaw != null) {
                    this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
                    this._yawRange = this._maxYaw - this._minYaw;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BoneLookController.prototype, "maxYaw", {
            /**
             * Gets or sets the maximum yaw angle that the bone can look to
             */
            get: function () {
                return this._maxYaw;
            },
            set: function (value) {
                this._maxYaw = value;
                this._maxYawSin = Math.sin(value);
                this._maxYawCos = Math.cos(value);
                if (this._minYaw != null) {
                    this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
                    this._yawRange = this._maxYaw - this._minYaw;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BoneLookController.prototype, "minPitch", {
            /**
             * Gets or sets the minimum pitch angle that the bone can look to
             */
            get: function () {
                return this._minPitch;
            },
            set: function (value) {
                this._minPitch = value;
                this._minPitchTan = Math.tan(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BoneLookController.prototype, "maxPitch", {
            /**
             * Gets or sets the maximum pitch angle that the bone can look to
             */
            get: function () {
                return this._maxPitch;
            },
            set: function (value) {
                this._maxPitch = value;
                this._maxPitchTan = Math.tan(value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Update the bone to look at the target.  This should be called before the scene is rendered (use scene.registerBeforeRender())
         */
        BoneLookController.prototype.update = function () {
            //skip the first frame when slerping so that the mesh rotation is correct
            if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
                this._firstFrameSkipped = true;
                return;
            }
            var bone = this.bone;
            var bonePos = BoneLookController._tmpVecs[0];
            bone.getAbsolutePositionToRef(this.mesh, bonePos);
            var target = this.target;
            var _tmpMat1 = BoneLookController._tmpMats[0];
            var _tmpMat2 = BoneLookController._tmpMats[1];
            var mesh = this.mesh;
            var parentBone = bone.getParent();
            var upAxis = BoneLookController._tmpVecs[1];
            upAxis.copyFrom(this.upAxis);
            if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
                if (this._transformYawPitch) {
                    BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
                }
                parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
            }
            else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
                mesh.getDirectionToRef(upAxis, upAxis);
                if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
                    upAxis.normalize();
                }
            }
            var checkYaw = false;
            var checkPitch = false;
            if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
                checkYaw = true;
            }
            if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
                checkPitch = true;
            }
            if (checkYaw || checkPitch) {
                var spaceMat = BoneLookController._tmpMats[2];
                var spaceMatInv = BoneLookController._tmpMats[3];
                if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
                    parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
                }
                else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
                    spaceMat.copyFrom(mesh.getWorldMatrix());
                }
                else {
                    var forwardAxis = BoneLookController._tmpVecs[2];
                    forwardAxis.copyFrom(this._fowardAxis);
                    if (this._transformYawPitch) {
                        BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
                    }
                    if (parentBone) {
                        parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
                    }
                    else {
                        mesh.getDirectionToRef(forwardAxis, forwardAxis);
                    }
                    var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
                    rightAxis.normalize();
                    var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
                    BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
                }
                spaceMat.invertToRef(spaceMatInv);
                var xzlen = null;
                if (checkPitch) {
                    var localTarget = BoneLookController._tmpVecs[3];
                    target.subtractToRef(bonePos, localTarget);
                    BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
                    xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
                    var pitch = Math.atan2(localTarget.y, xzlen);
                    var newPitch = pitch;
                    if (pitch > this._maxPitch) {
                        localTarget.y = this._maxPitchTan * xzlen;
                        newPitch = this._maxPitch;
                    }
                    else if (pitch < this._minPitch) {
                        localTarget.y = this._minPitchTan * xzlen;
                        newPitch = this._minPitch;
                    }
                    if (pitch != newPitch) {
                        BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
                        localTarget.addInPlace(bonePos);
                        target = localTarget;
                    }
                }
                if (checkYaw) {
                    var localTarget = BoneLookController._tmpVecs[4];
                    target.subtractToRef(bonePos, localTarget);
                    BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
                    var yaw = Math.atan2(localTarget.x, localTarget.z);
                    var newYaw = yaw;
                    if (yaw > this._maxYaw || yaw < this._minYaw) {
                        if (xzlen == null) {
                            xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
                        }
                        if (this._yawRange > Math.PI) {
                            if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
                                localTarget.z = this._maxYawCos * xzlen;
                                localTarget.x = this._maxYawSin * xzlen;
                                newYaw = this._maxYaw;
                            }
                            else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
                                localTarget.z = this._minYawCos * xzlen;
                                localTarget.x = this._minYawSin * xzlen;
                                newYaw = this._minYaw;
                            }
                        }
                        else {
                            if (yaw > this._maxYaw) {
                                localTarget.z = this._maxYawCos * xzlen;
                                localTarget.x = this._maxYawSin * xzlen;
                                newYaw = this._maxYaw;
                            }
                            else if (yaw < this._minYaw) {
                                localTarget.z = this._minYawCos * xzlen;
                                localTarget.x = this._minYawSin * xzlen;
                                newYaw = this._minYaw;
                            }
                        }
                    }
                    if (this._slerping && this._yawRange > Math.PI) {
                        //are we going to be crossing into the min/max region?
                        var boneFwd = BoneLookController._tmpVecs[8];
                        boneFwd.copyFrom(BABYLON.Axis.Z);
                        if (this._transformYawPitch) {
                            BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
                        }
                        var boneRotMat = BoneLookController._tmpMats[4];
                        this._boneQuat.toRotationMatrix(boneRotMat);
                        this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
                        BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
                        BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
                        var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
                        var angBtwTar = this._getAngleBetween(boneYaw, yaw);
                        var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
                        if (angBtwTar > angBtwMidYaw) {
                            if (xzlen == null) {
                                xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
                            }
                            var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
                            var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
                            if (angBtwMin < angBtwMax) {
                                newYaw = boneYaw + Math.PI * .75;
                                localTarget.z = Math.cos(newYaw) * xzlen;
                                localTarget.x = Math.sin(newYaw) * xzlen;
                            }
                            else {
                                newYaw = boneYaw - Math.PI * .75;
                                localTarget.z = Math.cos(newYaw) * xzlen;
                                localTarget.x = Math.sin(newYaw) * xzlen;
                            }
                        }
                    }
                    if (yaw != newYaw) {
                        BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
                        localTarget.addInPlace(bonePos);
                        target = localTarget;
                    }
                }
            }
            var zaxis = BoneLookController._tmpVecs[5];
            var xaxis = BoneLookController._tmpVecs[6];
            var yaxis = BoneLookController._tmpVecs[7];
            var _tmpQuat = BoneLookController._tmpQuat;
            target.subtractToRef(bonePos, zaxis);
            zaxis.normalize();
            BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
            xaxis.normalize();
            BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
            yaxis.normalize();
            BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
            if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
                return;
            }
            if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
                return;
            }
            if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
                return;
            }
            if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
                BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
                _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
            }
            if (this.slerpAmount < 1) {
                if (!this._slerping) {
                    this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
                }
                if (this._transformYawPitch) {
                    this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
                }
                BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
                BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
                this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
                this._slerping = true;
            }
            else {
                if (this._transformYawPitch) {
                    this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
                }
                this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
                this._slerping = false;
            }
        };
        BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
            var angDiff = ang2 - ang1;
            angDiff %= Math.PI * 2;
            if (angDiff > Math.PI) {
                angDiff -= Math.PI * 2;
            }
            else if (angDiff < -Math.PI) {
                angDiff += Math.PI * 2;
            }
            return angDiff;
        };
        BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
            ang1 %= (2 * Math.PI);
            ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
            ang2 %= (2 * Math.PI);
            ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
            var ab = 0;
            if (ang1 < ang2) {
                ab = ang2 - ang1;
            }
            else {
                ab = ang1 - ang2;
            }
            if (ab > Math.PI) {
                ab = Math.PI * 2 - ab;
            }
            return ab;
        };
        BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
            ang %= (2 * Math.PI);
            ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
            ang1 %= (2 * Math.PI);
            ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
            ang2 %= (2 * Math.PI);
            ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
            if (ang1 < ang2) {
                if (ang > ang1 && ang < ang2) {
                    return true;
                }
            }
            else {
                if (ang > ang2 && ang < ang1) {
                    return true;
                }
            }
            return false;
        };
        BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
        BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
        BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
        return BoneLookController;
    }());
    BABYLON.BoneLookController = BoneLookController;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boneLookController.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to handle skinning animations
     * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
     */
    var Skeleton = /** @class */ (function () {
        /**
         * Creates a new skeleton
         * @param name defines the skeleton name
         * @param id defines the skeleton Id
         * @param scene defines the hosting scene
         */
        function Skeleton(
        /** defines the skeleton name */
        name, 
        /** defines the skeleton Id */
        id, scene) {
            this.name = name;
            this.id = id;
            /**
             * Gets the list of child bones
             */
            this.bones = new Array();
            /**
             * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
             */
            this.needInitialSkinMatrix = false;
            this._isDirty = true;
            this._meshesWithPoseMatrix = new Array();
            this._identity = BABYLON.Matrix.Identity();
            this._ranges = {};
            this._lastAbsoluteTransformsUpdateId = -1;
            /**
             * Specifies if the skeleton should be serialized
             */
            this.doNotSerialize = false;
            this._animationPropertiesOverride = null;
            // Events
            /**
             * An observable triggered before computing the skeleton's matrices
             */
            this.onBeforeComputeObservable = new BABYLON.Observable();
            this.bones = [];
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            scene.skeletons.push(this);
            //make sure it will recalculate the matrix next time prepare is called.
            this._isDirty = true;
        }
        Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
            /**
             * Gets or sets the animation properties override
             */
            get: function () {
                if (!this._animationPropertiesOverride) {
                    return this._scene.animationPropertiesOverride;
                }
                return this._animationPropertiesOverride;
            },
            set: function (value) {
                this._animationPropertiesOverride = value;
            },
            enumerable: true,
            configurable: true
        });
        // Members
        /**
         * Gets the list of transform matrices to send to shaders (one matrix per bone)
         * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
         * @returns a Float32Array containing matrices data
         */
        Skeleton.prototype.getTransformMatrices = function (mesh) {
            if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
                return mesh._bonesTransformMatrices;
            }
            if (!this._transformMatrices) {
                this.prepare();
            }
            return this._transformMatrices;
        };
        /**
         * Gets the current hosting scene
         * @returns a scene object
         */
        Skeleton.prototype.getScene = function () {
            return this._scene;
        };
        // Methods
        /**
         * Gets a string representing the current skeleton data
         * @param fullDetails defines a boolean indicating if we want a verbose version
         * @returns a string representing the current skeleton data
         */
        Skeleton.prototype.toString = function (fullDetails) {
            var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
            ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
            if (fullDetails) {
                ret += ", Ranges: {";
                var first = true;
                for (var name_1 in this._ranges) {
                    if (first) {
                        ret += ", ";
                        first = false;
                    }
                    ret += name_1;
                }
                ret += "}";
            }
            return ret;
        };
        /**
        * Get bone's index searching by name
        * @param name defines bone's name to search for
        * @return the indice of the bone. Returns -1 if not found
        */
        Skeleton.prototype.getBoneIndexByName = function (name) {
            for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
                if (this.bones[boneIndex].name === name) {
                    return boneIndex;
                }
            }
            return -1;
        };
        /**
         * Creater a new animation range
         * @param name defines the name of the range
         * @param from defines the start key
         * @param to defines the end key
         */
        Skeleton.prototype.createAnimationRange = function (name, from, to) {
            // check name not already in use
            if (!this._ranges[name]) {
                this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
                for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
                    if (this.bones[i].animations[0]) {
                        this.bones[i].animations[0].createRange(name, from, to);
                    }
                }
            }
        };
        /**
         * Delete a specific animation range
         * @param name defines the name of the range
         * @param deleteFrames defines if frames must be removed as well
         */
        Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
            if (deleteFrames === void 0) { deleteFrames = true; }
            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
                if (this.bones[i].animations[0]) {
                    this.bones[i].animations[0].deleteRange(name, deleteFrames);
                }
            }
            this._ranges[name] = null; // said much faster than 'delete this._range[name]'
        };
        /**
         * Gets a specific animation range
         * @param name defines the name of the range to look for
         * @returns the requested animation range or null if not found
         */
        Skeleton.prototype.getAnimationRange = function (name) {
            return this._ranges[name];
        };
        /**
         * Gets the list of all animation ranges defined on this skeleton
         * @returns an array
         */
        Skeleton.prototype.getAnimationRanges = function () {
            var animationRanges = [];
            var name;
            var i = 0;
            for (name in this._ranges) {
                animationRanges[i] = this._ranges[name];
                i++;
            }
            return animationRanges;
        };
        /**
         * Copy animation range from a source skeleton.
         * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
         * @param source defines the source skeleton
         * @param name defines the name of the range to copy
         * @param rescaleAsRequired defines if rescaling must be applied if required
         * @returns true if operation was successful
         */
        Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
            if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
            if (this._ranges[name] || !source.getAnimationRange(name)) {
                return false;
            }
            var ret = true;
            var frameOffset = this._getHighestAnimationFrame() + 1;
            // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
            var boneDict = {};
            var sourceBones = source.bones;
            var nBones;
            var i;
            for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
                boneDict[sourceBones[i].name] = sourceBones[i];
            }
            if (this.bones.length !== sourceBones.length) {
                BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
                ret = false;
            }
            var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
            for (i = 0, nBones = this.bones.length; i < nBones; i++) {
                var boneName = this.bones[i].name;
                var sourceBone = boneDict[boneName];
                if (sourceBone) {
                    ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
                }
                else {
                    BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
                    ret = false;
                }
            }
            // do not call createAnimationRange(), since it also is done to bones, which was already done
            var range = source.getAnimationRange(name);
            if (range) {
                this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
            }
            return ret;
        };
        /**
         * Forces the skeleton to go to rest pose
         */
        Skeleton.prototype.returnToRest = function () {
            for (var index = 0; index < this.bones.length; index++) {
                this.bones[index].returnToRest();
            }
        };
        Skeleton.prototype._getHighestAnimationFrame = function () {
            var ret = 0;
            for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
                if (this.bones[i].animations[0]) {
                    var highest = this.bones[i].animations[0].getHighestFrame();
                    if (ret < highest) {
                        ret = highest;
                    }
                }
            }
            return ret;
        };
        /**
         * Begin a specific animation range
         * @param name defines the name of the range to start
         * @param loop defines if looping must be turned on (false by default)
         * @param speedRatio defines the speed ratio to apply (1 by default)
         * @param onAnimationEnd defines a callback which will be called when animation will end
         * @returns a new animatable
         */
        Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
            var range = this.getAnimationRange(name);
            if (!range) {
                return null;
            }
            return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
        };
        /** @hidden */
        Skeleton.prototype._markAsDirty = function () {
            this._isDirty = true;
        };
        /** @hidden */
        Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
            this._meshesWithPoseMatrix.push(mesh);
        };
        /** @hidden */
        Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
            var index = this._meshesWithPoseMatrix.indexOf(mesh);
            if (index > -1) {
                this._meshesWithPoseMatrix.splice(index, 1);
            }
        };
        /** @hidden */
        Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
            this.onBeforeComputeObservable.notifyObservers(this);
            for (var index = 0; index < this.bones.length; index++) {
                var bone = this.bones[index];
                var parentBone = bone.getParent();
                if (parentBone) {
                    bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
                }
                else {
                    if (initialSkinMatrix) {
                        bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
                    }
                    else {
                        bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
                    }
                }
                if (bone._index !== -1) {
                    var mappedIndex = bone._index === null ? index : bone._index;
                    bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
                }
            }
            this._identity.copyToArray(targetMatrix, this.bones.length * 16);
        };
        /**
         * Build all resources required to render a skeleton
         */
        Skeleton.prototype.prepare = function () {
            if (!this._isDirty) {
                return;
            }
            if (this.needInitialSkinMatrix) {
                for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
                    var mesh = this._meshesWithPoseMatrix[index];
                    var poseMatrix = mesh.getPoseMatrix();
                    if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
                        mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
                    }
                    if (this._synchronizedWithMesh !== mesh) {
                        this._synchronizedWithMesh = mesh;
                        // Prepare bones
                        for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
                            var bone = this.bones[boneIndex];
                            if (!bone.getParent()) {
                                var matrix = bone.getBaseMatrix();
                                matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
                                bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
                            }
                        }
                    }
                    this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
                }
            }
            else {
                if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
                    this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
                }
                this._computeTransformMatrices(this._transformMatrices, null);
            }
            this._isDirty = false;
            this._scene._activeBones.addCount(this.bones.length, false);
        };
        /**
         * Gets the list of animatables currently running for this skeleton
         * @returns an array of animatables
         */
        Skeleton.prototype.getAnimatables = function () {
            if (!this._animatables || this._animatables.length !== this.bones.length) {
                this._animatables = [];
                for (var index = 0; index < this.bones.length; index++) {
                    this._animatables.push(this.bones[index]);
                }
            }
            return this._animatables;
        };
        /**
         * Clone the current skeleton
         * @param name defines the name of the new skeleton
         * @param id defines the id of the enw skeleton
         * @returns the new skeleton
         */
        Skeleton.prototype.clone = function (name, id) {
            var result = new Skeleton(name, id || name, this._scene);
            result.needInitialSkinMatrix = this.needInitialSkinMatrix;
            for (var index = 0; index < this.bones.length; index++) {
                var source = this.bones[index];
                var parentBone = null;
                var parent_1 = source.getParent();
                if (parent_1) {
                    var parentIndex = this.bones.indexOf(parent_1);
                    parentBone = result.bones[parentIndex];
                }
                var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
                BABYLON.Tools.DeepCopy(source.animations, bone.animations);
            }
            if (this._ranges) {
                result._ranges = {};
                for (var rangeName in this._ranges) {
                    var range = this._ranges[rangeName];
                    if (range) {
                        result._ranges[rangeName] = range.clone();
                    }
                }
            }
            this._isDirty = true;
            return result;
        };
        /**
         * Enable animation blending for this skeleton
         * @param blendingSpeed defines the blending speed to apply
         * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
         */
        Skeleton.prototype.enableBlending = function (blendingSpeed) {
            if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
            this.bones.forEach(function (bone) {
                bone.animations.forEach(function (animation) {
                    animation.enableBlending = true;
                    animation.blendingSpeed = blendingSpeed;
                });
            });
        };
        /**
         * Releases all resources associated with the current skeleton
         */
        Skeleton.prototype.dispose = function () {
            this._meshesWithPoseMatrix = [];
            // Animations
            this.getScene().stopAnimation(this);
            // Remove from scene
            this.getScene().removeSkeleton(this);
        };
        /**
         * Serialize the skeleton in a JSON object
         * @returns a JSON object
         */
        Skeleton.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.id = this.id;
            if (this.dimensionsAtRest) {
                serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
            }
            serializationObject.bones = [];
            serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
            for (var index = 0; index < this.bones.length; index++) {
                var bone = this.bones[index];
                var parent_2 = bone.getParent();
                var serializedBone = {
                    parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
                    name: bone.name,
                    matrix: bone.getBaseMatrix().toArray(),
                    rest: bone.getRestPose().toArray()
                };
                serializationObject.bones.push(serializedBone);
                if (bone.length) {
                    serializedBone.length = bone.length;
                }
                if (bone.metadata) {
                    serializedBone.metadata = bone.metadata;
                }
                if (bone.animations && bone.animations.length > 0) {
                    serializedBone.animation = bone.animations[0].serialize();
                }
                serializationObject.ranges = [];
                for (var name in this._ranges) {
                    var source = this._ranges[name];
                    if (!source) {
                        continue;
                    }
                    var range = {};
                    range.name = name;
                    range.from = source.from;
                    range.to = source.to;
                    serializationObject.ranges.push(range);
                }
            }
            return serializationObject;
        };
        /**
         * Creates a new skeleton from serialized data
         * @param parsedSkeleton defines the serialized data
         * @param scene defines the hosting scene
         * @returns a new skeleton
         */
        Skeleton.Parse = function (parsedSkeleton, scene) {
            var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
            if (parsedSkeleton.dimensionsAtRest) {
                skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
            }
            skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
            var index;
            for (index = 0; index < parsedSkeleton.bones.length; index++) {
                var parsedBone = parsedSkeleton.bones[index];
                var parentBone = null;
                if (parsedBone.parentBoneIndex > -1) {
                    parentBone = skeleton.bones[parsedBone.parentBoneIndex];
                }
                var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
                var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
                if (parsedBone.id !== undefined && parsedBone.id !== null) {
                    bone.id = parsedBone.id;
                }
                if (parsedBone.length) {
                    bone.length = parsedBone.length;
                }
                if (parsedBone.metadata) {
                    bone.metadata = parsedBone.metadata;
                }
                if (parsedBone.animation) {
                    bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
                }
            }
            // placed after bones, so createAnimationRange can cascade down
            if (parsedSkeleton.ranges) {
                for (index = 0; index < parsedSkeleton.ranges.length; index++) {
                    var data = parsedSkeleton.ranges[index];
                    skeleton.createAnimationRange(data.name, data.from, data.to);
                }
            }
            return skeleton;
        };
        /**
         * Compute all node absolute transforms
         * @param forceUpdate defines if computation must be done even if cache is up to date
         */
        Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
            if (forceUpdate === void 0) { forceUpdate = false; }
            var renderId = this._scene.getRenderId();
            if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
                this.bones[0].computeAbsoluteTransforms();
                this._lastAbsoluteTransformsUpdateId = renderId;
            }
        };
        /**
         * Gets the root pose matrix
         * @returns a matrix
         */
        Skeleton.prototype.getPoseMatrix = function () {
            var poseMatrix = null;
            if (this._meshesWithPoseMatrix.length > 0) {
                poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
            }
            return poseMatrix;
        };
        /**
         * Sorts bones per internal index
         */
        Skeleton.prototype.sortBones = function () {
            var bones = new Array();
            var visited = new Array(this.bones.length);
            for (var index = 0; index < this.bones.length; index++) {
                this._sortBones(index, bones, visited);
            }
            this.bones = bones;
        };
        Skeleton.prototype._sortBones = function (index, bones, visited) {
            if (visited[index]) {
                return;
            }
            visited[index] = true;
            var bone = this.bones[index];
            if (bone._index === undefined) {
                bone._index = index;
            }
            var parentBone = bone.getParent();
            if (parentBone) {
                this._sortBones(this.bones.indexOf(parentBone), bones, visited);
            }
            bones.push(bone);
        };
        return Skeleton;
    }());
    BABYLON.Skeleton = Skeleton;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.skeleton.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This groups tools to convert HDR texture to native colors array.
     */
    var HDRTools = /** @class */ (function () {
        function HDRTools() {
        }
        HDRTools.Ldexp = function (mantissa, exponent) {
            if (exponent > 1023) {
                return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
            }
            if (exponent < -1074) {
                return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
            }
            return mantissa * Math.pow(2, exponent);
        };
        HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
            if (exponent > 0) { /*nonzero pixel*/
                exponent = this.Ldexp(1.0, exponent - (128 + 8));
                float32array[index + 0] = red * exponent;
                float32array[index + 1] = green * exponent;
                float32array[index + 2] = blue * exponent;
            }
            else {
                float32array[index + 0] = 0;
                float32array[index + 1] = 0;
                float32array[index + 2] = 0;
            }
        };
        HDRTools.readStringLine = function (uint8array, startIndex) {
            var line = "";
            var character = "";
            for (var i = startIndex; i < uint8array.length - startIndex; i++) {
                character = String.fromCharCode(uint8array[i]);
                if (character == "\n") {
                    break;
                }
                line += character;
            }
            return line;
        };
        /**
         * Reads header information from an RGBE texture stored in a native array.
         * More information on this format are available here:
         * https://en.wikipedia.org/wiki/RGBE_image_format
         *
         * @param uint8array The binary file stored in  native array.
         * @return The header information.
         */
        HDRTools.RGBE_ReadHeader = function (uint8array) {
            var height = 0;
            var width = 0;
            var line = this.readStringLine(uint8array, 0);
            if (line[0] != '#' || line[1] != '?') {
                throw "Bad HDR Format.";
            }
            var endOfHeader = false;
            var findFormat = false;
            var lineIndex = 0;
            do {
                lineIndex += (line.length + 1);
                line = this.readStringLine(uint8array, lineIndex);
                if (line == "FORMAT=32-bit_rle_rgbe") {
                    findFormat = true;
                }
                else if (line.length == 0) {
                    endOfHeader = true;
                }
            } while (!endOfHeader);
            if (!findFormat) {
                throw "HDR Bad header format, unsupported FORMAT";
            }
            lineIndex += (line.length + 1);
            line = this.readStringLine(uint8array, lineIndex);
            var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
            var match = sizeRegexp.exec(line);
            // TODO. Support +Y and -X if needed.
            if (!match || match.length < 3) {
                throw "HDR Bad header format, no size";
            }
            width = parseInt(match[2]);
            height = parseInt(match[1]);
            if (width < 8 || width > 0x7fff) {
                throw "HDR Bad header format, unsupported size";
            }
            lineIndex += (line.length + 1);
            return {
                height: height,
                width: width,
                dataPosition: lineIndex
            };
        };
        /**
         * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
         * This RGBE texture needs to store the information as a panorama.
         *
         * More information on this format are available here:
         * https://en.wikipedia.org/wiki/RGBE_image_format
         *
         * @param buffer The binary file stored in an array buffer.
         * @param size The expected size of the extracted cubemap.
         * @return The Cube Map information.
         */
        HDRTools.GetCubeMapTextureData = function (buffer, size) {
            var uint8array = new Uint8Array(buffer);
            var hdrInfo = this.RGBE_ReadHeader(uint8array);
            var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
            var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
            return cubeMapData;
        };
        /**
         * Returns the pixels data extracted from an RGBE texture.
         * This pixels will be stored left to right up to down in the R G B order in one array.
         *
         * More information on this format are available here:
         * https://en.wikipedia.org/wiki/RGBE_image_format
         *
         * @param uint8array The binary file stored in an array buffer.
         * @param hdrInfo The header information of the file.
         * @return The pixels data in RGB right to left up to down order.
         */
        HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
            // Keep for multi format supports.
            return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
        };
        HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
            var num_scanlines = hdrInfo.height;
            var scanline_width = hdrInfo.width;
            var a, b, c, d, count;
            var dataIndex = hdrInfo.dataPosition;
            var index = 0, endIndex = 0, i = 0;
            var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
            var scanLineArray = new Uint8Array(scanLineArrayBuffer);
            // 3 channels of 4 bytes per pixel in float.
            var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
            var resultArray = new Float32Array(resultBuffer);
            // read in each successive scanline
            while (num_scanlines > 0) {
                a = uint8array[dataIndex++];
                b = uint8array[dataIndex++];
                c = uint8array[dataIndex++];
                d = uint8array[dataIndex++];
                if (a != 2 || b != 2 || (c & 0x80)) {
                    // this file is not run length encoded
                    throw "HDR Bad header format, not RLE";
                }
                if (((c << 8) | d) != scanline_width) {
                    throw "HDR Bad header format, wrong scan line width";
                }
                index = 0;
                // read each of the four channels for the scanline into the buffer
                for (i = 0; i < 4; i++) {
                    endIndex = (i + 1) * scanline_width;
                    while (index < endIndex) {
                        a = uint8array[dataIndex++];
                        b = uint8array[dataIndex++];
                        if (a > 128) {
                            // a run of the same value
                            count = a - 128;
                            if ((count == 0) || (count > endIndex - index)) {
                                throw "HDR Bad Format, bad scanline data (run)";
                            }
                            while (count-- > 0) {
                                scanLineArray[index++] = b;
                            }
                        }
                        else {
                            // a non-run
                            count = a;
                            if ((count == 0) || (count > endIndex - index)) {
                                throw "HDR Bad Format, bad scanline data (non-run)";
                            }
                            scanLineArray[index++] = b;
                            if (--count > 0) {
                                for (var j = 0; j < count; j++) {
                                    scanLineArray[index++] = uint8array[dataIndex++];
                                }
                            }
                        }
                    }
                }
                // now convert data from buffer into floats
                for (i = 0; i < scanline_width; i++) {
                    a = scanLineArray[i];
                    b = scanLineArray[i + scanline_width];
                    c = scanLineArray[i + 2 * scanline_width];
                    d = scanLineArray[i + 3 * scanline_width];
                    this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
                }
                num_scanlines--;
            }
            return resultArray;
        };
        return HDRTools;
    }());
    BABYLON.HDRTools = HDRTools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.hdr.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This represents a texture coming from an HDR input.
     *
     * The only supported format is currently panorama picture stored in RGBE format.
     * Example of such files can be found on HDRLib: http://hdrlib.com/
     */
    var HDRCubeTexture = /** @class */ (function (_super) {
        __extends(HDRCubeTexture, _super);
        /**
         * Instantiates an HDRTexture from the following parameters.
         *
         * @param url The location of the HDR raw data (Panorama stored in RGBE format)
         * @param scene The scene the texture will be used in
         * @param size The cubemap desired size (the more it increases the longer the generation will be)
         * @param noMipmap Forces to not generate the mipmap if true
         * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
         * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
         * @param reserved Reserved flag for internal use.
         */
        function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
            if (noMipmap === void 0) { noMipmap = false; }
            if (generateHarmonics === void 0) { generateHarmonics = true; }
            if (gammaSpace === void 0) { gammaSpace = false; }
            if (reserved === void 0) { reserved = false; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            var _this = _super.call(this, scene) || this;
            _this._generateHarmonics = true;
            _this._onLoad = null;
            _this._onError = null;
            /**
             * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
             */
            _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
            _this._isBlocking = true;
            _this._rotationY = 0;
            /**
             * Gets or sets the center of the bounding box associated with the cube texture
             * It must define where the camera used to render the texture was set
             */
            _this.boundingBoxPosition = BABYLON.Vector3.Zero();
            if (!url) {
                return _this;
            }
            _this.name = url;
            _this.url = url;
            _this.hasAlpha = false;
            _this.isCube = true;
            _this._textureMatrix = BABYLON.Matrix.Identity();
            _this._onLoad = onLoad;
            _this._onError = onError;
            _this.gammaSpace = gammaSpace;
            _this._noMipmap = noMipmap;
            _this._size = size;
            _this._texture = _this._getFromCache(url, _this._noMipmap);
            if (!_this._texture) {
                if (!scene.useDelayedTextureLoading) {
                    _this.loadTexture();
                }
                else {
                    _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
                }
            }
            return _this;
        }
        Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
            /**
             * Gets wether or not the texture is blocking during loading.
             */
            get: function () {
                return this._isBlocking;
            },
            /**
             * Sets wether or not the texture is blocking during loading.
             */
            set: function (value) {
                this._isBlocking = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
            /**
             * Gets texture matrix rotation angle around Y axis radians.
             */
            get: function () {
                return this._rotationY;
            },
            /**
             * Sets texture matrix rotation angle around Y axis in radians.
             */
            set: function (value) {
                this._rotationY = value;
                this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
            get: function () {
                return this._boundingBoxSize;
            },
            /**
             * Gets or sets the size of the bounding box associated with the cube texture
             * When defined, the cubemap will switch to local mode
             * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
             * @example https://www.babylonjs-playground.com/#RNASML
             */
            set: function (value) {
                if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
                    return;
                }
                this._boundingBoxSize = value;
                var scene = this.getScene();
                if (scene) {
                    scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Occurs when the file is raw .hdr file.
         */
        HDRCubeTexture.prototype.loadTexture = function () {
            var _this = this;
            var callback = function (buffer) {
                _this.lodGenerationOffset = 0.0;
                _this.lodGenerationScale = 0.8;
                var scene = _this.getScene();
                if (!scene) {
                    return null;
                }
                // Extract the raw linear data.
                var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
                // Generate harmonics if needed.
                if (_this._generateHarmonics) {
                    var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
                    _this.sphericalPolynomial = sphericalPolynomial;
                }
                var results = [];
                var byteArray = null;
                // Push each faces.
                for (var j = 0; j < 6; j++) {
                    // Create uintarray fallback.
                    if (!scene.getEngine().getCaps().textureFloat) {
                        // 3 channels of 1 bytes per pixel in bytes.
                        var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
                        byteArray = new Uint8Array(byteBuffer);
                    }
                    var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
                    // If special cases.
                    if (_this.gammaSpace || byteArray) {
                        for (var i = 0; i < _this._size * _this._size; i++) {
                            // Put in gamma space if requested.
                            if (_this.gammaSpace) {
                                dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
                                dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
                                dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
                            }
                            // Convert to int texture for fallback.
                            if (byteArray) {
                                var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
                                var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
                                var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
                                // May use luminance instead if the result is not accurate.
                                var max = Math.max(Math.max(r, g), b);
                                if (max > 255) {
                                    var scale = 255 / max;
                                    r *= scale;
                                    g *= scale;
                                    b *= scale;
                                }
                                byteArray[(i * 3) + 0] = r;
                                byteArray[(i * 3) + 1] = g;
                                byteArray[(i * 3) + 2] = b;
                            }
                        }
                    }
                    if (byteArray) {
                        results.push(byteArray);
                    }
                    else {
                        results.push(dataFace);
                    }
                }
                return results;
            };
            var scene = this.getScene();
            if (scene) {
                this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
            }
        };
        HDRCubeTexture.prototype.clone = function () {
            var scene = this.getScene();
            if (!scene) {
                return this;
            }
            var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
            // Base texture
            newTexture.level = this.level;
            newTexture.wrapU = this.wrapU;
            newTexture.wrapV = this.wrapV;
            newTexture.coordinatesIndex = this.coordinatesIndex;
            newTexture.coordinatesMode = this.coordinatesMode;
            return newTexture;
        };
        // Methods
        HDRCubeTexture.prototype.delayLoad = function () {
            if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
                return;
            }
            this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
            this._texture = this._getFromCache(this.url, this._noMipmap);
            if (!this._texture) {
                this.loadTexture();
            }
        };
        /**
         * Get the texture reflection matrix used to rotate/transform the reflection.
         * @returns the reflection matrix
         */
        HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
            return this._textureMatrix;
        };
        /**
         * Set the texture reflection matrix used to rotate/transform the reflection.
         * @param value Define the reflection matrix to set
         */
        HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
            this._textureMatrix = value;
        };
        /**
         * Parses a JSON representation of an HDR Texture in order to create the texture
         * @param parsedTexture Define the JSON representation
         * @param scene Define the scene the texture should be created in
         * @param rootUrl Define the root url in case we need to load relative dependencies
         * @returns the newly created texture after parsing
         */
        HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
            var texture = null;
            if (parsedTexture.name && !parsedTexture.isRenderTarget) {
                texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
                texture.name = parsedTexture.name;
                texture.hasAlpha = parsedTexture.hasAlpha;
                texture.level = parsedTexture.level;
                texture.coordinatesMode = parsedTexture.coordinatesMode;
                texture.isBlocking = parsedTexture.isBlocking;
            }
            if (texture) {
                if (parsedTexture.boundingBoxPosition) {
                    texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
                }
                if (parsedTexture.boundingBoxSize) {
                    texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
                }
                if (parsedTexture.rotationY) {
                    texture.rotationY = parsedTexture.rotationY;
                }
            }
            return texture;
        };
        HDRCubeTexture.prototype.serialize = function () {
            if (!this.name) {
                return null;
            }
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.hasAlpha = this.hasAlpha;
            serializationObject.isCube = true;
            serializationObject.level = this.level;
            serializationObject.size = this._size;
            serializationObject.coordinatesMode = this.coordinatesMode;
            serializationObject.useInGammaSpace = this.gammaSpace;
            serializationObject.generateHarmonics = this._generateHarmonics;
            serializationObject.customType = "BABYLON.HDRCubeTexture";
            serializationObject.noMipmap = this._noMipmap;
            serializationObject.isBlocking = this._isBlocking;
            serializationObject.rotationY = this._rotationY;
            return serializationObject;
        };
        HDRCubeTexture._facesMapping = [
            "right",
            "left",
            "up",
            "down",
            "front",
            "back"
        ];
        return HDRCubeTexture;
    }(BABYLON.BaseTexture));
    BABYLON.HDRCubeTexture = HDRCubeTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.hdrCubeTexture.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
     */
    var PanoramaToCubeMapTools = /** @class */ (function () {
        function PanoramaToCubeMapTools() {
        }
        /**
         * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
         *
         * @param float32Array The source data.
         * @param inputWidth The width of the input panorama.
         * @param inputHeight The height of the input panorama.
         * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
         * @return The cubemap data
         */
        PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
            if (!float32Array) {
                throw "ConvertPanoramaToCubemap: input cannot be null";
            }
            if (float32Array.length != inputWidth * inputHeight * 3) {
                throw "ConvertPanoramaToCubemap: input size is wrong";
            }
            var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
            var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
            var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
            var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
            var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
            var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
            return {
                front: textureFront,
                back: textureBack,
                left: textureLeft,
                right: textureRight,
                up: textureUp,
                down: textureDown,
                size: size,
                type: BABYLON.Engine.TEXTURETYPE_FLOAT,
                format: BABYLON.Engine.TEXTUREFORMAT_RGB,
                gammaSpace: false,
            };
        };
        PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
            var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
            var textureArray = new Float32Array(buffer);
            var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
            var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
            var dy = 1 / texSize;
            var fy = 0;
            for (var y = 0; y < texSize; y++) {
                var xv1 = faceData[0];
                var xv2 = faceData[2];
                for (var x = 0; x < texSize; x++) {
                    var v = xv2.subtract(xv1).scale(fy).add(xv1);
                    v.normalize();
                    var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
                    // 3 channels per pixels
                    textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
                    textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
                    textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
                    xv1 = xv1.add(rotDX1);
                    xv2 = xv2.add(rotDX2);
                }
                fy += dy;
            }
            return textureArray;
        };
        PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
            var theta = Math.atan2(vDir.z, vDir.x);
            var phi = Math.acos(vDir.y);
            while (theta < -Math.PI) {
                theta += 2 * Math.PI;
            }
            while (theta > Math.PI) {
                theta -= 2 * Math.PI;
            }
            var dx = theta / Math.PI;
            var dy = phi / Math.PI;
            // recenter.
            dx = dx * 0.5 + 0.5;
            var px = Math.round(dx * inputWidth);
            if (px < 0) {
                px = 0;
            }
            else if (px >= inputWidth) {
                px = inputWidth - 1;
            }
            var py = Math.round(dy * inputHeight);
            if (py < 0) {
                py = 0;
            }
            else if (py >= inputHeight) {
                py = inputHeight - 1;
            }
            var inputY = (inputHeight - py - 1);
            var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
            var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
            var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
            return {
                r: r,
                g: g,
                b: b
            };
        };
        PanoramaToCubeMapTools.FACE_FRONT = [
            new BABYLON.Vector3(-1.0, -1.0, -1.0),
            new BABYLON.Vector3(1.0, -1.0, -1.0),
            new BABYLON.Vector3(-1.0, 1.0, -1.0),
            new BABYLON.Vector3(1.0, 1.0, -1.0)
        ];
        PanoramaToCubeMapTools.FACE_BACK = [
            new BABYLON.Vector3(1.0, -1.0, 1.0),
            new BABYLON.Vector3(-1.0, -1.0, 1.0),
            new BABYLON.Vector3(1.0, 1.0, 1.0),
            new BABYLON.Vector3(-1.0, 1.0, 1.0)
        ];
        PanoramaToCubeMapTools.FACE_RIGHT = [
            new BABYLON.Vector3(1.0, -1.0, -1.0),
            new BABYLON.Vector3(1.0, -1.0, 1.0),
            new BABYLON.Vector3(1.0, 1.0, -1.0),
            new BABYLON.Vector3(1.0, 1.0, 1.0)
        ];
        PanoramaToCubeMapTools.FACE_LEFT = [
            new BABYLON.Vector3(-1.0, -1.0, 1.0),
            new BABYLON.Vector3(-1.0, -1.0, -1.0),
            new BABYLON.Vector3(-1.0, 1.0, 1.0),
            new BABYLON.Vector3(-1.0, 1.0, -1.0)
        ];
        PanoramaToCubeMapTools.FACE_DOWN = [
            new BABYLON.Vector3(-1.0, 1.0, -1.0),
            new BABYLON.Vector3(1.0, 1.0, -1.0),
            new BABYLON.Vector3(-1.0, 1.0, 1.0),
            new BABYLON.Vector3(1.0, 1.0, 1.0)
        ];
        PanoramaToCubeMapTools.FACE_UP = [
            new BABYLON.Vector3(-1.0, -1.0, 1.0),
            new BABYLON.Vector3(1.0, -1.0, 1.0),
            new BABYLON.Vector3(-1.0, -1.0, -1.0),
            new BABYLON.Vector3(1.0, -1.0, -1.0)
        ];
        return PanoramaToCubeMapTools;
    }());
    BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.panoramaToCubemap.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Vector2 wth index property
     */
    var IndexedVector2 = /** @class */ (function (_super) {
        __extends(IndexedVector2, _super);
        function IndexedVector2(original, 
        /** Index of the vector2 */
        index) {
            var _this = _super.call(this, original.x, original.y) || this;
            _this.index = index;
            return _this;
        }
        return IndexedVector2;
    }(BABYLON.Vector2));
    /**
     * Defines points to create a polygon
     */
    var PolygonPoints = /** @class */ (function () {
        function PolygonPoints() {
            this.elements = new Array();
        }
        PolygonPoints.prototype.add = function (originalPoints) {
            var _this = this;
            var result = new Array();
            originalPoints.forEach(function (point) {
                if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
                    var newPoint = new IndexedVector2(point, _this.elements.length);
                    result.push(newPoint);
                    _this.elements.push(newPoint);
                }
            });
            return result;
        };
        PolygonPoints.prototype.computeBounds = function () {
            var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
            var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
            this.elements.forEach(function (point) {
                // x
                if (point.x < lmin.x) {
                    lmin.x = point.x;
                }
                else if (point.x > lmax.x) {
                    lmax.x = point.x;
                }
                // y
                if (point.y < lmin.y) {
                    lmin.y = point.y;
                }
                else if (point.y > lmax.y) {
                    lmax.y = point.y;
                }
            });
            return {
                min: lmin,
                max: lmax,
                width: lmax.x - lmin.x,
                height: lmax.y - lmin.y
            };
        };
        return PolygonPoints;
    }());
    /**
     * Polygon
     * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
     */
    var Polygon = /** @class */ (function () {
        function Polygon() {
        }
        /**
         * Creates a rectangle
         * @param xmin bottom X coord
         * @param ymin bottom Y coord
         * @param xmax top X coord
         * @param ymax top Y coord
         * @returns points that make the resulting rectation
         */
        Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
            return [
                new BABYLON.Vector2(xmin, ymin),
                new BABYLON.Vector2(xmax, ymin),
                new BABYLON.Vector2(xmax, ymax),
                new BABYLON.Vector2(xmin, ymax)
            ];
        };
        /**
         * Creates a circle
         * @param radius radius of circle
         * @param cx scale in x
         * @param cy scale in y
         * @param numberOfSides number of sides that make up the circle
         * @returns points that make the resulting circle
         */
        Polygon.Circle = function (radius, cx, cy, numberOfSides) {
            if (cx === void 0) { cx = 0; }
            if (cy === void 0) { cy = 0; }
            if (numberOfSides === void 0) { numberOfSides = 32; }
            var result = new Array();
            var angle = 0;
            var increment = (Math.PI * 2) / numberOfSides;
            for (var i = 0; i < numberOfSides; i++) {
                result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
                angle -= increment;
            }
            return result;
        };
        /**
         * Creates a polygon from input string
         * @param input Input polygon data
         * @returns the parsed points
         */
        Polygon.Parse = function (input) {
            var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
            var i, result = [];
            for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
                result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
            }
            return result;
        };
        /**
         * Starts building a polygon from x and y coordinates
         * @param x x coordinate
         * @param y y coordinate
         * @returns the started path2
         */
        Polygon.StartingAt = function (x, y) {
            return BABYLON.Path2.StartingAt(x, y);
        };
        return Polygon;
    }());
    BABYLON.Polygon = Polygon;
    /**
     * Builds a polygon
     * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
     */
    var PolygonMeshBuilder = /** @class */ (function () {
        /**
         * Creates a PolygonMeshBuilder
         * @param name name of the builder
         * @param contours Path of the polygon
         * @param scene scene to add to
         */
        function PolygonMeshBuilder(name, contours, scene) {
            this._points = new PolygonPoints();
            this._outlinepoints = new PolygonPoints();
            this._holes = new Array();
            this._epoints = new Array();
            this._eholes = new Array();
            this._name = name;
            this._scene = scene;
            var points;
            if (contours instanceof BABYLON.Path2) {
                points = contours.getPoints();
            }
            else {
                points = contours;
            }
            this._addToepoint(points);
            this._points.add(points);
            this._outlinepoints.add(points);
            if (typeof earcut === 'undefined') {
                BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
            }
        }
        PolygonMeshBuilder.prototype._addToepoint = function (points) {
            for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
                var p = points_1[_i];
                this._epoints.push(p.x, p.y);
            }
        };
        /**
         * Adds a whole within the polygon
         * @param hole Array of points defining the hole
         * @returns this
         */
        PolygonMeshBuilder.prototype.addHole = function (hole) {
            this._points.add(hole);
            var holepoints = new PolygonPoints();
            holepoints.add(hole);
            this._holes.push(holepoints);
            this._eholes.push(this._epoints.length / 2);
            this._addToepoint(hole);
            return this;
        };
        /**
         * Creates the polygon
         * @param updatable If the mesh should be updatable
         * @param depth The depth of the mesh created
         * @returns the created mesh
         */
        PolygonMeshBuilder.prototype.build = function (updatable, depth) {
            var _this = this;
            if (updatable === void 0) { updatable = false; }
            if (depth === void 0) { depth = 0; }
            var result = new BABYLON.Mesh(this._name, this._scene);
            var normals = new Array();
            var positions = new Array();
            var uvs = new Array();
            var bounds = this._points.computeBounds();
            this._points.elements.forEach(function (p) {
                normals.push(0, 1.0, 0);
                positions.push(p.x, 0, p.y);
                uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
            });
            var indices = new Array();
            var res = earcut(this._epoints, this._eholes, 2);
            for (var i = 0; i < res.length; i++) {
                indices.push(res[i]);
            }
            if (depth > 0) {
                var positionscount = (positions.length / 3); //get the current pointcount
                this._points.elements.forEach(function (p) {
                    normals.push(0, -1.0, 0);
                    positions.push(p.x, -depth, p.y);
                    uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
                });
                var totalCount = indices.length;
                for (var i = 0; i < totalCount; i += 3) {
                    var i0 = indices[i + 0];
                    var i1 = indices[i + 1];
                    var i2 = indices[i + 2];
                    indices.push(i2 + positionscount);
                    indices.push(i1 + positionscount);
                    indices.push(i0 + positionscount);
                }
                //Add the sides
                this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
                this._holes.forEach(function (hole) {
                    _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
                });
            }
            result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
            result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
            result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
            result.setIndices(indices);
            return result;
        };
        /**
         * Adds a side to the polygon
         * @param positions points that make the polygon
         * @param normals normals of the polygon
         * @param uvs uvs of the polygon
         * @param indices indices of the polygon
         * @param bounds bounds of the polygon
         * @param points points of the polygon
         * @param depth depth of the polygon
         * @param flip flip of the polygon
         */
        PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
            var StartIndex = positions.length / 3;
            var ulength = 0;
            for (var i = 0; i < points.elements.length; i++) {
                var p = points.elements[i];
                var p1;
                if ((i + 1) > points.elements.length - 1) {
                    p1 = points.elements[0];
                }
                else {
                    p1 = points.elements[i + 1];
                }
                positions.push(p.x, 0, p.y);
                positions.push(p.x, -depth, p.y);
                positions.push(p1.x, 0, p1.y);
                positions.push(p1.x, -depth, p1.y);
                var v1 = new BABYLON.Vector3(p.x, 0, p.y);
                var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
                var v3 = v2.subtract(v1);
                var v4 = new BABYLON.Vector3(0, 1, 0);
                var vn = BABYLON.Vector3.Cross(v3, v4);
                vn = vn.normalize();
                uvs.push(ulength / bounds.width, 0);
                uvs.push(ulength / bounds.width, 1);
                ulength += v3.length();
                uvs.push((ulength / bounds.width), 0);
                uvs.push((ulength / bounds.width), 1);
                if (!flip) {
                    normals.push(-vn.x, -vn.y, -vn.z);
                    normals.push(-vn.x, -vn.y, -vn.z);
                    normals.push(-vn.x, -vn.y, -vn.z);
                    normals.push(-vn.x, -vn.y, -vn.z);
                    indices.push(StartIndex);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 2);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 3);
                    indices.push(StartIndex + 2);
                }
                else {
                    normals.push(vn.x, vn.y, vn.z);
                    normals.push(vn.x, vn.y, vn.z);
                    normals.push(vn.x, vn.y, vn.z);
                    normals.push(vn.x, vn.y, vn.z);
                    indices.push(StartIndex);
                    indices.push(StartIndex + 2);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 1);
                    indices.push(StartIndex + 2);
                    indices.push(StartIndex + 3);
                }
                StartIndex += 4;
            }
        };
        return PolygonMeshBuilder;
    }());
    BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.polygonMesh.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Unique ID when we import meshes from Babylon to CSG
     */
    var currentCSGMeshId = 0;
    /**
     * Represents a vertex of a polygon. Use your own vertex class instead of this
     * one to provide additional features like texture coordinates and vertex
     * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
     * `flip()`, and `interpolate()` methods that behave analogous to the ones
     * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
     * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
     * is not used anywhere else.
     * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
     */
    var Vertex = /** @class */ (function () {
        /**
         * Initializes the vertex
         * @param pos The position of the vertex
         * @param normal The normal of the vertex
         * @param uv The texture coordinate of the vertex
         */
        function Vertex(
        /**
         * The position of the vertex
         */
        pos, 
        /**
         * The normal of the vertex
         */
        normal, 
        /**
         * The texture coordinate of the vertex
         */
        uv) {
            this.pos = pos;
            this.normal = normal;
            this.uv = uv;
        }
        /**
         * Make a clone, or deep copy, of the vertex
         * @returns A new Vertex
         */
        Vertex.prototype.clone = function () {
            return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
        };
        /**
         * Invert all orientation-specific data (e.g. vertex normal). Called when the
         * orientation of a polygon is flipped.
         */
        Vertex.prototype.flip = function () {
            this.normal = this.normal.scale(-1);
        };
        /**
         * Create a new vertex between this vertex and `other` by linearly
         * interpolating all properties using a parameter of `t`. Subclasses should
         * override this to interpolate additional properties.
         * @param other the vertex to interpolate against
         * @param t The factor used to linearly interpolate between the vertices
         */
        Vertex.prototype.interpolate = function (other, t) {
            return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
        };
        return Vertex;
    }());
    /**
     * Represents a plane in 3D space.
     */
    var Plane = /** @class */ (function () {
        /**
         * Initializes the plane
         * @param normal The normal for the plane
         * @param w
         */
        function Plane(normal, w) {
            this.normal = normal;
            this.w = w;
        }
        /**
         * Construct a plane from three points
         * @param a Point a
         * @param b Point b
         * @param c Point c
         */
        Plane.FromPoints = function (a, b, c) {
            var v0 = c.subtract(a);
            var v1 = b.subtract(a);
            if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
                return null;
            }
            var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
            return new Plane(n, BABYLON.Vector3.Dot(n, a));
        };
        /**
         * Clone, or make a deep copy of the plane
         * @returns a new Plane
         */
        Plane.prototype.clone = function () {
            return new Plane(this.normal.clone(), this.w);
        };
        /**
         * Flip the face of the plane
         */
        Plane.prototype.flip = function () {
            this.normal.scaleInPlace(-1);
            this.w = -this.w;
        };
        /**
         * Split `polygon` by this plane if needed, then put the polygon or polygon
         * fragments in the appropriate lists. Coplanar polygons go into either
        `* coplanarFront` or `coplanarBack` depending on their orientation with
         * respect to this plane. Polygons in front or in back of this plane go into
         * either `front` or `back`
         * @param polygon The polygon to be split
         * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
         * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
         * @param front Will contain the polygons in front of the plane
         * @param back Will contain the polygons begind the plane
         */
        Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
            var COPLANAR = 0;
            var FRONT = 1;
            var BACK = 2;
            var SPANNING = 3;
            // Classify each point as well as the entire polygon into one of the above
            // four classes.
            var polygonType = 0;
            var types = [];
            var i;
            var t;
            for (i = 0; i < polygon.vertices.length; i++) {
                t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
                var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
                polygonType |= type;
                types.push(type);
            }
            // Put the polygon in the correct list, splitting it when necessary
            switch (polygonType) {
                case COPLANAR:
                    (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
                    break;
                case FRONT:
                    front.push(polygon);
                    break;
                case BACK:
                    back.push(polygon);
                    break;
                case SPANNING:
                    var f = [], b = [];
                    for (i = 0; i < polygon.vertices.length; i++) {
                        var j = (i + 1) % polygon.vertices.length;
                        var ti = types[i], tj = types[j];
                        var vi = polygon.vertices[i], vj = polygon.vertices[j];
                        if (ti !== BACK) {
                            f.push(vi);
                        }
                        if (ti !== FRONT) {
                            b.push(ti !== BACK ? vi.clone() : vi);
                        }
                        if ((ti | tj) === SPANNING) {
                            t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
                            var v = vi.interpolate(vj, t);
                            f.push(v);
                            b.push(v.clone());
                        }
                    }
                    var poly;
                    if (f.length >= 3) {
                        poly = new Polygon(f, polygon.shared);
                        if (poly.plane) {
                            front.push(poly);
                        }
                    }
                    if (b.length >= 3) {
                        poly = new Polygon(b, polygon.shared);
                        if (poly.plane) {
                            back.push(poly);
                        }
                    }
                    break;
            }
        };
        /**
         * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
         * point is on the plane
         */
        Plane.EPSILON = 1e-5;
        return Plane;
    }());
    /**
     * Represents a convex polygon. The vertices used to initialize a polygon must
     * be coplanar and form a convex loop.
     *
     * Each convex polygon has a `shared` property, which is shared between all
     * polygons that are clones of each other or were split from the same polygon.
     * This can be used to define per-polygon properties (such as surface color)
     */
    var Polygon = /** @class */ (function () {
        /**
         * Initializes the polygon
         * @param vertices The vertices of the polygon
         * @param shared The properties shared across all polygons
         */
        function Polygon(vertices, shared) {
            this.vertices = vertices;
            this.shared = shared;
            this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
        }
        /**
         * Clones, or makes a deep copy, or the polygon
         */
        Polygon.prototype.clone = function () {
            var vertices = this.vertices.map(function (v) { return v.clone(); });
            return new Polygon(vertices, this.shared);
        };
        /**
         * Flips the faces of the polygon
         */
        Polygon.prototype.flip = function () {
            this.vertices.reverse().map(function (v) { v.flip(); });
            this.plane.flip();
        };
        return Polygon;
    }());
    /**
     * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
     * by picking a polygon to split along. That polygon (and all other coplanar
     * polygons) are added directly to that node and the other polygons are added to
     * the front and/or back subtrees. This is not a leafy BSP tree since there is
     * no distinction between internal and leaf nodes
     */
    var Node = /** @class */ (function () {
        /**
         * Initializes the node
         * @param polygons A collection of polygons held in the node
         */
        function Node(polygons) {
            this.plane = null;
            this.front = null;
            this.back = null;
            this.polygons = new Array();
            if (polygons) {
                this.build(polygons);
            }
        }
        /**
         * Clones, or makes a deep copy, of the node
         * @returns The cloned node
         */
        Node.prototype.clone = function () {
            var node = new Node();
            node.plane = this.plane && this.plane.clone();
            node.front = this.front && this.front.clone();
            node.back = this.back && this.back.clone();
            node.polygons = this.polygons.map(function (p) { return p.clone(); });
            return node;
        };
        /**
         * Convert solid space to empty space and empty space to solid space
         */
        Node.prototype.invert = function () {
            for (var i = 0; i < this.polygons.length; i++) {
                this.polygons[i].flip();
            }
            if (this.plane) {
                this.plane.flip();
            }
            if (this.front) {
                this.front.invert();
            }
            if (this.back) {
                this.back.invert();
            }
            var temp = this.front;
            this.front = this.back;
            this.back = temp;
        };
        /**
         * Recursively remove all polygons in `polygons` that are inside this BSP
         * tree.
         * @param polygons Polygons to remove from the BSP
         * @returns Polygons clipped from the BSP
         */
        Node.prototype.clipPolygons = function (polygons) {
            if (!this.plane) {
                return polygons.slice();
            }
            var front = new Array(), back = new Array();
            for (var i = 0; i < polygons.length; i++) {
                this.plane.splitPolygon(polygons[i], front, back, front, back);
            }
            if (this.front) {
                front = this.front.clipPolygons(front);
            }
            if (this.back) {
                back = this.back.clipPolygons(back);
            }
            else {
                back = [];
            }
            return front.concat(back);
        };
        /**
         * Remove all polygons in this BSP tree that are inside the other BSP tree
         * `bsp`.
         * @param bsp BSP containing polygons to remove from this BSP
         */
        Node.prototype.clipTo = function (bsp) {
            this.polygons = bsp.clipPolygons(this.polygons);
            if (this.front) {
                this.front.clipTo(bsp);
            }
            if (this.back) {
                this.back.clipTo(bsp);
            }
        };
        /**
         * Return a list of all polygons in this BSP tree
         * @returns List of all polygons in this BSP tree
         */
        Node.prototype.allPolygons = function () {
            var polygons = this.polygons.slice();
            if (this.front) {
                polygons = polygons.concat(this.front.allPolygons());
            }
            if (this.back) {
                polygons = polygons.concat(this.back.allPolygons());
            }
            return polygons;
        };
        /**
         * Build a BSP tree out of `polygons`. When called on an existing tree, the
         * new polygons are filtered down to the bottom of the tree and become new
         * nodes there. Each set of polygons is partitioned using the first polygon
         * (no heuristic is used to pick a good split)
         * @param polygons Polygons used to construct the BSP tree
         */
        Node.prototype.build = function (polygons) {
            if (!polygons.length) {
                return;
            }
            if (!this.plane) {
                this.plane = polygons[0].plane.clone();
            }
            var front = new Array(), back = new Array();
            for (var i = 0; i < polygons.length; i++) {
                this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
            }
            if (front.length) {
                if (!this.front) {
                    this.front = new Node();
                }
                this.front.build(front);
            }
            if (back.length) {
                if (!this.back) {
                    this.back = new Node();
                }
                this.back.build(back);
            }
        };
        return Node;
    }());
    /**
     * Class for building Constructive Solid Geometry
     */
    var CSG = /** @class */ (function () {
        function CSG() {
            this.polygons = new Array();
        }
        /**
         * Convert the BABYLON.Mesh to BABYLON.CSG
         * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
         * @returns A new BABYLON.CSG from the BABYLON.Mesh
         */
        CSG.FromMesh = function (mesh) {
            var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
            var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
            if (mesh instanceof BABYLON.Mesh) {
                mesh.computeWorldMatrix(true);
                matrix = mesh.getWorldMatrix();
                meshPosition = mesh.position.clone();
                meshRotation = mesh.rotation.clone();
                if (mesh.rotationQuaternion) {
                    meshRotationQuaternion = mesh.rotationQuaternion.clone();
                }
                meshScaling = mesh.scaling.clone();
            }
            else {
                throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
            }
            var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var subMeshes = mesh.subMeshes;
            for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
                for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
                    vertices = [];
                    for (var j = 0; j < 3; j++) {
                        var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
                        uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
                        var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
                        position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
                        normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
                        vertex = new Vertex(position, normal, uv);
                        vertices.push(vertex);
                    }
                    polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
                    // To handle the case of degenerated triangle
                    // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
                    if (polygon.plane) {
                        polygons.push(polygon);
                    }
                }
            }
            var csg = CSG.FromPolygons(polygons);
            csg.matrix = matrix;
            csg.position = meshPosition;
            csg.rotation = meshRotation;
            csg.scaling = meshScaling;
            csg.rotationQuaternion = meshRotationQuaternion;
            currentCSGMeshId++;
            return csg;
        };
        /**
         * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
         * @param polygons Polygons used to construct a BABYLON.CSG solid
         */
        CSG.FromPolygons = function (polygons) {
            var csg = new CSG();
            csg.polygons = polygons;
            return csg;
        };
        /**
         * Clones, or makes a deep copy, of the BABYLON.CSG
         * @returns A new BABYLON.CSG
         */
        CSG.prototype.clone = function () {
            var csg = new CSG();
            csg.polygons = this.polygons.map(function (p) { return p.clone(); });
            csg.copyTransformAttributes(this);
            return csg;
        };
        /**
         * Unions this CSG with another CSG
         * @param csg The CSG to union against this CSG
         * @returns The unioned CSG
         */
        CSG.prototype.union = function (csg) {
            var a = new Node(this.clone().polygons);
            var b = new Node(csg.clone().polygons);
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
        };
        /**
         * Unions this CSG with another CSG in place
         * @param csg The CSG to union against this CSG
         */
        CSG.prototype.unionInPlace = function (csg) {
            var a = new Node(this.polygons);
            var b = new Node(csg.polygons);
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            this.polygons = a.allPolygons();
        };
        /**
         * Subtracts this CSG with another CSG
         * @param csg The CSG to subtract against this CSG
         * @returns A new BABYLON.CSG
         */
        CSG.prototype.subtract = function (csg) {
            var a = new Node(this.clone().polygons);
            var b = new Node(csg.clone().polygons);
            a.invert();
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            a.invert();
            return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
        };
        /**
         * Subtracts this CSG with another CSG in place
         * @param csg The CSG to subtact against this CSG
         */
        CSG.prototype.subtractInPlace = function (csg) {
            var a = new Node(this.polygons);
            var b = new Node(csg.polygons);
            a.invert();
            a.clipTo(b);
            b.clipTo(a);
            b.invert();
            b.clipTo(a);
            b.invert();
            a.build(b.allPolygons());
            a.invert();
            this.polygons = a.allPolygons();
        };
        /**
         * Intersect this CSG with another CSG
         * @param csg The CSG to intersect against this CSG
         * @returns A new BABYLON.CSG
         */
        CSG.prototype.intersect = function (csg) {
            var a = new Node(this.clone().polygons);
            var b = new Node(csg.clone().polygons);
            a.invert();
            b.clipTo(a);
            b.invert();
            a.clipTo(b);
            b.clipTo(a);
            a.build(b.allPolygons());
            a.invert();
            return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
        };
        /**
         * Intersects this CSG with another CSG in place
         * @param csg The CSG to intersect against this CSG
         */
        CSG.prototype.intersectInPlace = function (csg) {
            var a = new Node(this.polygons);
            var b = new Node(csg.polygons);
            a.invert();
            b.clipTo(a);
            b.invert();
            a.clipTo(b);
            b.clipTo(a);
            a.build(b.allPolygons());
            a.invert();
            this.polygons = a.allPolygons();
        };
        /**
         * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
         * not modified.
         * @returns A new BABYLON.CSG solid with solid and empty space switched
         */
        CSG.prototype.inverse = function () {
            var csg = this.clone();
            csg.inverseInPlace();
            return csg;
        };
        /**
         * Inverses the BABYLON.CSG in place
         */
        CSG.prototype.inverseInPlace = function () {
            this.polygons.map(function (p) { p.flip(); });
        };
        /**
         * This is used to keep meshes transformations so they can be restored
         * when we build back a Babylon Mesh
         * NB : All CSG operations are performed in world coordinates
         * @param csg The BABYLON.CSG to copy the transform attributes from
         * @returns This BABYLON.CSG
         */
        CSG.prototype.copyTransformAttributes = function (csg) {
            this.matrix = csg.matrix;
            this.position = csg.position;
            this.rotation = csg.rotation;
            this.scaling = csg.scaling;
            this.rotationQuaternion = csg.rotationQuaternion;
            return this;
        };
        /**
         * Build Raw mesh from CSG
         * Coordinates here are in world space
         * @param name The name of the mesh geometry
         * @param scene The BABYLON.Scene
         * @param keepSubMeshes Specifies if the submeshes should be kept
         * @returns A new BABYLON.Mesh
         */
        CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
            var matrix = this.matrix.clone();
            matrix.invert();
            var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
            if (keepSubMeshes) {
                // Sort Polygons, since subMeshes are indices range
                polygons.sort(function (a, b) {
                    if (a.shared.meshId === b.shared.meshId) {
                        return a.shared.subMeshId - b.shared.subMeshId;
                    }
                    else {
                        return a.shared.meshId - b.shared.meshId;
                    }
                });
            }
            for (var i = 0, il = polygons.length; i < il; i++) {
                polygon = polygons[i];
                // Building SubMeshes
                if (!subMesh_dict[polygon.shared.meshId]) {
                    subMesh_dict[polygon.shared.meshId] = {};
                }
                if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
                    subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
                        indexStart: +Infinity,
                        indexEnd: -Infinity,
                        materialIndex: polygon.shared.materialIndex
                    };
                }
                subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
                for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
                    polygonIndices[0] = 0;
                    polygonIndices[1] = j - 1;
                    polygonIndices[2] = j;
                    for (var k = 0; k < 3; k++) {
                        vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
                        normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
                        uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
                        var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
                        var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
                        vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
                        // Check if 2 points can be merged
                        if (!(typeof vertex_idx !== 'undefined' &&
                            normals[vertex_idx * 3] === localNormal.x &&
                            normals[vertex_idx * 3 + 1] === localNormal.y &&
                            normals[vertex_idx * 3 + 2] === localNormal.z &&
                            uvs[vertex_idx * 2] === uv.x &&
                            uvs[vertex_idx * 2 + 1] === uv.y)) {
                            vertices.push(localVertex.x, localVertex.y, localVertex.z);
                            uvs.push(uv.x, uv.y);
                            normals.push(normal.x, normal.y, normal.z);
                            vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
                        }
                        indices.push(vertex_idx);
                        subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
                        subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
                        currentIndex++;
                    }
                }
            }
            mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
            mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
            mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
            mesh.setIndices(indices, null);
            if (keepSubMeshes) {
                // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
                var materialIndexOffset = 0, materialMaxIndex;
                mesh.subMeshes = new Array();
                for (var m in subMesh_dict) {
                    materialMaxIndex = -1;
                    for (var sm in subMesh_dict[m]) {
                        subMesh_obj = subMesh_dict[m][sm];
                        BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
                        materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
                    }
                    materialIndexOffset += ++materialMaxIndex;
                }
            }
            return mesh;
        };
        /**
         * Build Mesh from CSG taking material and transforms into account
         * @param name The name of the BABYLON.Mesh
         * @param material The material of the BABYLON.Mesh
         * @param scene The BABYLON.Scene
         * @param keepSubMeshes Specifies if submeshes should be kept
         * @returns The new BABYLON.Mesh
         */
        CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
            var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
            mesh.material = material;
            mesh.position.copyFrom(this.position);
            mesh.rotation.copyFrom(this.rotation);
            if (this.rotationQuaternion) {
                mesh.rotationQuaternion = this.rotationQuaternion.clone();
            }
            mesh.scaling.copyFrom(this.scaling);
            mesh.computeWorldMatrix(true);
            return mesh;
        };
        return CSG;
    }());
    BABYLON.CSG = CSG;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.csg.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
     * It controls one of the indiviual texture used in the effect.
     * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
     */
    var LensFlare = /** @class */ (function () {
        /**
         * Instantiates a new Lens Flare.
         * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
         * It controls one of the indiviual texture used in the effect.
         * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
         * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
         * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
         * @param color Define the lens color
         * @param imgUrl Define the lens texture url
         * @param system Define the `lensFlareSystem` this flare is part of
         */
        function LensFlare(
        /**
         * Define the size of the lens flare in the system (a floating value between 0 and 1)
         */
        size, 
        /**
         * Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
         */
        position, color, imgUrl, system) {
            this.size = size;
            this.position = position;
            /**
             * Define the alpha mode to render this particular lens.
             */
            this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
            this.color = color || new BABYLON.Color3(1, 1, 1);
            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
            this._system = system;
            system.lensFlares.push(this);
        }
        /**
         * Creates a new Lens Flare.
         * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
         * It controls one of the indiviual texture used in the effect.
         * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
         * @param size Define the size of the lens flare (a floating value between 0 and 1)
         * @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
         * @param color Define the lens color
         * @param imgUrl Define the lens texture url
         * @param system Define the `lensFlareSystem` this flare is part of
         * @returns The newly created Lens Flare
         */
        LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
            return new LensFlare(size, position, color, imgUrl, system);
        };
        /**
         * Dispose and release the lens flare with its associated resources.
         */
        LensFlare.prototype.dispose = function () {
            if (this.texture) {
                this.texture.dispose();
            }
            // Remove from scene
            var index = this._system.lensFlares.indexOf(this);
            this._system.lensFlares.splice(index, 1);
        };
        return LensFlare;
    }());
    BABYLON.LensFlare = LensFlare;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.lensFlare.js.map

var BABYLON;
(function (BABYLON) {
    // Adds the parser to the scene parsers.
    BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
        // Lens flares
        if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
            if (!container.lensFlareSystems) {
                container.lensFlareSystems = new Array();
            }
            for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
                var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
                var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
                container.lensFlareSystems.push(lf);
            }
        }
    });
    BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
        for (var index = 0; index < this.lensFlareSystems.length; index++) {
            if (this.lensFlareSystems[index].name === name) {
                return this.lensFlareSystems[index];
            }
        }
        return null;
    };
    BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
        for (var index = 0; index < this.lensFlareSystems.length; index++) {
            if (this.lensFlareSystems[index].id === id) {
                return this.lensFlareSystems[index];
            }
        }
        return null;
    };
    BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
        var index = this.lensFlareSystems.indexOf(toRemove);
        if (index !== -1) {
            this.lensFlareSystems.splice(index, 1);
        }
        return index;
    };
    BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
        this.lensFlareSystems.push(newLensFlareSystem);
    };
    /**
     * Defines the lens flare scene component responsible to manage any lens flares
     * in a given scene.
     */
    var LensFlareSystemSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function LensFlareSystemSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
            this.scene = scene;
            scene.lensFlareSystems = new Array();
        }
        /**
         * Registers the component in a given scene
         */
        LensFlareSystemSceneComponent.prototype.register = function () {
            this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        LensFlareSystemSceneComponent.prototype.rebuild = function () {
            // Nothing to do for lens flare
        };
        /**
         * Adds all the element from the container to the scene
         * @param container the container holding the elements
         */
        LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
            var _this = this;
            if (!container.lensFlareSystems) {
                return;
            }
            container.lensFlareSystems.forEach(function (o) {
                _this.scene.addLensFlareSystem(o);
            });
        };
        /**
         * Removes all the elements in the container from the scene
         * @param container contains the elements to remove
         */
        LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
            var _this = this;
            if (!container.lensFlareSystems) {
                return;
            }
            container.lensFlareSystems.forEach(function (o) {
                _this.scene.removeLensFlareSystem(o);
            });
        };
        /**
         * Serializes the component data to the specified json object
         * @param serializationObject The object to serialize to
         */
        LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
            // Lens flares
            serializationObject.lensFlareSystems = [];
            var lensFlareSystems = this.scene.lensFlareSystems;
            for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
                var lensFlareSystem = lensFlareSystems_1[_i];
                serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
            }
        };
        /**
         * Disposes the component and the associated ressources.
         */
        LensFlareSystemSceneComponent.prototype.dispose = function () {
            var lensFlareSystems = this.scene.lensFlareSystems;
            while (lensFlareSystems.length) {
                lensFlareSystems[0].dispose();
            }
        };
        LensFlareSystemSceneComponent.prototype._draw = function (camera) {
            // Lens flares
            if (this.scene.lensFlaresEnabled) {
                var lensFlareSystems = this.scene.lensFlareSystems;
                BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
                for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
                    var lensFlareSystem = lensFlareSystems_2[_i];
                    if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
                        lensFlareSystem.render();
                    }
                }
                BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
            }
        };
        return LensFlareSystemSceneComponent;
    }());
    BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents a Lens Flare System or the shiny effect created by the light reflection on the  camera lenses.
     * It is usually composed of several `BABYLON.lensFlare`.
     * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
     */
    var LensFlareSystem = /** @class */ (function () {
        /**
         * Instantiates a lens flare system.
         * This represents a Lens Flare System or the shiny effect created by the light reflection on the  camera lenses.
         * It is usually composed of several `BABYLON.lensFlare`.
         * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
         * @param name Define the name of the lens flare system in the scene
         * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
         * @param scene Define the scene the lens flare system belongs to
         */
        function LensFlareSystem(
        /**
         * Define the name of the lens flare system
         */
        name, emitter, scene) {
            this.name = name;
            /**
             * List of lens flares used in this system.
             */
            this.lensFlares = new Array();
            /**
             * Define a limit from the border the lens flare can be visible.
             */
            this.borderLimit = 300;
            /**
             * Define a viewport border we do not want to see the lens flare in.
             */
            this.viewportBorder = 0;
            /**
             * Restricts the rendering of the effect to only the camera rendering this layer mask.
             */
            this.layerMask = 0x0FFFFFFF;
            this._vertexBuffers = {};
            this._isEnabled = true;
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
            if (!component) {
                component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
                scene._addComponent(component);
            }
            this._emitter = emitter;
            this.id = name;
            scene.lensFlareSystems.push(this);
            this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
            var engine = scene.getEngine();
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
            // Effects
            this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
        }
        Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
            /**
             * Define if the lens flare system is enabled.
             */
            get: function () {
                return this._isEnabled;
            },
            set: function (value) {
                this._isEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get the scene the effects belongs to.
         * @returns the scene holding the lens flare system
         */
        LensFlareSystem.prototype.getScene = function () {
            return this._scene;
        };
        /**
         * Get the emitter of the lens flare system.
         * It defines the source of the lens flares (it can be a camera, a light or a mesh).
         * @returns the emitter of the lens flare system
         */
        LensFlareSystem.prototype.getEmitter = function () {
            return this._emitter;
        };
        /**
         * Set the emitter of the lens flare system.
         * It defines the source of the lens flares (it can be a camera, a light or a mesh).
         * @param newEmitter Define the new emitter of the system
         */
        LensFlareSystem.prototype.setEmitter = function (newEmitter) {
            this._emitter = newEmitter;
        };
        /**
         * Get the lens flare system emitter position.
         * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
         * @returns the position
         */
        LensFlareSystem.prototype.getEmitterPosition = function () {
            return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
        };
        /**
         * @hidden
         */
        LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
            var position = this.getEmitterPosition();
            position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
            this._positionX = position.x;
            this._positionY = position.y;
            position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
            if (this.viewportBorder > 0) {
                globalViewport.x -= this.viewportBorder;
                globalViewport.y -= this.viewportBorder;
                globalViewport.width += this.viewportBorder * 2;
                globalViewport.height += this.viewportBorder * 2;
                position.x += this.viewportBorder;
                position.y += this.viewportBorder;
                this._positionX += this.viewportBorder;
                this._positionY += this.viewportBorder;
            }
            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 true;
            }
            return false;
        };
        /** @hidden */
        LensFlareSystem.prototype._isVisible = function () {
            if (!this._isEnabled || !this._scene.activeCamera) {
                return false;
            }
            var emitterPosition = this.getEmitterPosition();
            var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
            var distance = direction.length();
            direction.normalize();
            var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
            var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
            return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
        };
        /**
         * @hidden
         */
        LensFlareSystem.prototype.render = function () {
            if (!this._effect.isReady() || !this._scene.activeCamera) {
                return false;
            }
            var engine = this._scene.getEngine();
            var viewport = this._scene.activeCamera.viewport;
            var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
            // Position
            if (!this.computeEffectivePosition(globalViewport)) {
                return false;
            }
            // Visibility
            if (!this._isVisible()) {
                return false;
            }
            // Intensity
            var awayX;
            var awayY;
            if (this._positionX < this.borderLimit + globalViewport.x) {
                awayX = this.borderLimit + globalViewport.x - this._positionX;
            }
            else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
                awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
            }
            else {
                awayX = 0;
            }
            if (this._positionY < this.borderLimit + globalViewport.y) {
                awayY = this.borderLimit + globalViewport.y - this._positionY;
            }
            else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
                awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
            }
            else {
                awayY = 0;
            }
            var away = (awayX > awayY) ? awayX : awayY;
            away -= this.viewportBorder;
            if (away > this.borderLimit) {
                away = this.borderLimit;
            }
            var intensity = 1.0 - BABYLON.Scalar.Clamp(away / this.borderLimit, 0, 1);
            if (intensity < 0) {
                return false;
            }
            if (intensity > 1.0) {
                intensity = 1.0;
            }
            if (this.viewportBorder > 0) {
                globalViewport.x += this.viewportBorder;
                globalViewport.y += this.viewportBorder;
                globalViewport.width -= this.viewportBorder * 2;
                globalViewport.height -= this.viewportBorder * 2;
                this._positionX -= this.viewportBorder;
                this._positionY -= this.viewportBorder;
            }
            // Position
            var centerX = globalViewport.x + globalViewport.width / 2;
            var centerY = globalViewport.y + globalViewport.height / 2;
            var distX = centerX - this._positionX;
            var distY = centerY - this._positionY;
            // Effects
            engine.enableEffect(this._effect);
            engine.setState(false);
            engine.setDepthBuffer(false);
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
            // Flares
            for (var index = 0; index < this.lensFlares.length; index++) {
                var flare = this.lensFlares[index];
                engine.setAlphaMode(flare.alphaMode);
                var x = centerX - (distX * flare.position);
                var y = centerY - (distY * flare.position);
                var cw = flare.size;
                var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
                var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
                var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
                var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
                this._effect.setMatrix("viewportMatrix", viewportMatrix);
                // Texture
                this._effect.setTexture("textureSampler", flare.texture);
                // Color
                this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
                // Draw order
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
            }
            engine.setDepthBuffer(true);
            engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            return true;
        };
        /**
         * Dispose and release the lens flare with its associated resources.
         */
        LensFlareSystem.prototype.dispose = function () {
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            while (this.lensFlares.length) {
                this.lensFlares[0].dispose();
            }
            // Remove from scene
            var index = this._scene.lensFlareSystems.indexOf(this);
            this._scene.lensFlareSystems.splice(index, 1);
        };
        /**
         * Parse a lens flare system from a JSON repressentation
         * @param parsedLensFlareSystem Define the JSON to parse
         * @param scene Define the scene the parsed system should be instantiated in
         * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
         * @returns the parsed system
         */
        LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
            var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
            var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
            var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
            lensFlareSystem.id = parsedLensFlareSystem.id || name;
            lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
            for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
                var parsedFlare = parsedLensFlareSystem.flares[index];
                BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
            }
            return lensFlareSystem;
        };
        /**
         * Serialize the current Lens Flare System into a JSON representation.
         * @returns the serialized JSON
         */
        LensFlareSystem.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.id = this.id;
            serializationObject.name = this.name;
            serializationObject.emitterId = this.getEmitter().id;
            serializationObject.borderLimit = this.borderLimit;
            serializationObject.flares = [];
            for (var index = 0; index < this.lensFlares.length; index++) {
                var flare = this.lensFlares[index];
                serializationObject.flares.push({
                    size: flare.size,
                    position: flare.position,
                    color: flare.color.asArray(),
                    textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
                });
            }
            return serializationObject;
        };
        return LensFlareSystem;
    }());
    BABYLON.LensFlareSystem = LensFlareSystem;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.lensFlareSystem.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * This is a holder class for the physics joint created by the physics plugin
     * It holds a set of functions to control the underlying joint
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsJoint = /** @class */ (function () {
        /**
         * Initializes the physics joint
         * @param type The type of the physics joint
         * @param jointData The data for the physics joint
         */
        function PhysicsJoint(
        /**
         * The type of the physics joint
         */
        type, 
        /**
         * The data for the physics joint
         */
        jointData) {
            this.type = type;
            this.jointData = jointData;
            jointData.nativeParams = jointData.nativeParams || {};
        }
        Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
            /**
             * Gets the physics joint
             */
            get: function () {
                return this._physicsJoint;
            },
            /**
             * Sets the physics joint
             */
            set: function (newJoint) {
                if (this._physicsJoint) {
                    //remove from the wolrd
                }
                this._physicsJoint = newJoint;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
            /**
             * Sets the physics plugin
             */
            set: function (physicsPlugin) {
                this._physicsPlugin = physicsPlugin;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Execute a function that is physics-plugin specific.
         * @param {Function} func the function that will be executed.
         *                        It accepts two parameters: the physics world and the physics joint
         */
        PhysicsJoint.prototype.executeNativeFunction = function (func) {
            func(this._physicsPlugin.world, this._physicsJoint);
        };
        //TODO check if the native joints are the same
        //Joint Types
        /**
         * Distance-Joint type
         */
        PhysicsJoint.DistanceJoint = 0;
        /**
         * Hinge-Joint type
         */
        PhysicsJoint.HingeJoint = 1;
        /**
         * Ball-and-Socket joint type
         */
        PhysicsJoint.BallAndSocketJoint = 2;
        /**
         * Wheel-Joint type
         */
        PhysicsJoint.WheelJoint = 3;
        /**
         * Slider-Joint type
         */
        PhysicsJoint.SliderJoint = 4;
        //OIMO
        /**
         * Prismatic-Joint type
         */
        PhysicsJoint.PrismaticJoint = 5;
        //
        /**
         * Universal-Joint type
         * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
         */
        PhysicsJoint.UniversalJoint = 6;
        /**
         * Hinge-Joint 2 type
         */
        PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
        //Cannon
        /**
         * Point to Point Joint type.  Similar to a Ball-Joint.  Different in parameters
         */
        PhysicsJoint.PointToPointJoint = 8;
        //Cannon only at the moment
        /**
         * Spring-Joint type
         */
        PhysicsJoint.SpringJoint = 9;
        /**
         * Lock-Joint type
         */
        PhysicsJoint.LockJoint = 10;
        return PhysicsJoint;
    }());
    BABYLON.PhysicsJoint = PhysicsJoint;
    /**
     * A class representing a physics distance joint
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var DistanceJoint = /** @class */ (function (_super) {
        __extends(DistanceJoint, _super);
        /**
         *
         * @param jointData The data for the Distance-Joint
         */
        function DistanceJoint(jointData) {
            return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
        }
        /**
         * Update the predefined distance.
         * @param maxDistance The maximum preferred distance
         * @param minDistance The minimum preferred distance
         */
        DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
            this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
        };
        return DistanceJoint;
    }(PhysicsJoint));
    BABYLON.DistanceJoint = DistanceJoint;
    /**
     * Represents a Motor-Enabled Joint
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var MotorEnabledJoint = /** @class */ (function (_super) {
        __extends(MotorEnabledJoint, _super);
        /**
         * Initializes the Motor-Enabled Joint
         * @param type The type of the joint
         * @param jointData The physica joint data for the joint
         */
        function MotorEnabledJoint(type, jointData) {
            return _super.call(this, type, jointData) || this;
        }
        /**
         * Set the motor values.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param force the force to apply
         * @param maxForce max force for this motor.
         */
        MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
            this._physicsPlugin.setMotor(this, force || 0, maxForce);
        };
        /**
         * Set the motor's limits.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param upperLimit The upper limit of the motor
         * @param lowerLimit The lower limit of the motor
         */
        MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
            this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
        };
        return MotorEnabledJoint;
    }(PhysicsJoint));
    BABYLON.MotorEnabledJoint = MotorEnabledJoint;
    /**
     * This class represents a single physics Hinge-Joint
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var HingeJoint = /** @class */ (function (_super) {
        __extends(HingeJoint, _super);
        /**
         * Initializes the Hinge-Joint
         * @param jointData The joint data for the Hinge-Joint
         */
        function HingeJoint(jointData) {
            return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
        }
        /**
         * Set the motor values.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} force the force to apply
         * @param {number} maxForce max force for this motor.
         */
        HingeJoint.prototype.setMotor = function (force, maxForce) {
            this._physicsPlugin.setMotor(this, force || 0, maxForce);
        };
        /**
         * Set the motor's limits.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param upperLimit The upper limit of the motor
         * @param lowerLimit The lower limit of the motor
         */
        HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
            this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
        };
        return HingeJoint;
    }(MotorEnabledJoint));
    BABYLON.HingeJoint = HingeJoint;
    /**
     * This class represents a dual hinge physics joint (same as wheel joint)
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var Hinge2Joint = /** @class */ (function (_super) {
        __extends(Hinge2Joint, _super);
        /**
         * Initializes the Hinge2-Joint
         * @param jointData The joint data for the Hinge2-Joint
         */
        function Hinge2Joint(jointData) {
            return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
        }
        /**
         * Set the motor values.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} force the force to apply
         * @param {number} maxForce max force for this motor.
         * @param {motorIndex} the motor's index, 0 or 1.
         */
        Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
            if (motorIndex === void 0) { motorIndex = 0; }
            this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
        };
        /**
         * Set the motor limits.
         * Attention, this function is plugin specific. Engines won't react 100% the same.
         * @param {number} upperLimit the upper limit
         * @param {number} lowerLimit lower limit
         * @param {motorIndex} the motor's index, 0 or 1.
         */
        Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
            if (motorIndex === void 0) { motorIndex = 0; }
            this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
        };
        return Hinge2Joint;
    }(MotorEnabledJoint));
    BABYLON.Hinge2Joint = Hinge2Joint;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.physicsJoint.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Represents a physics imposter
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsImpostor = /** @class */ (function () {
        /**
         * Initializes the physics imposter
         * @param object The physics-enabled object used as the physics imposter
         * @param type The type of the physics imposter
         * @param _options The options for the physics imposter
         * @param _scene The Babylon scene
         */
        function PhysicsImpostor(
        /**
         * The physics-enabled object used as the physics imposter
         */
        object, 
        /**
         * The type of the physics imposter
         */
        type, _options, _scene) {
            if (_options === void 0) { _options = { mass: 0 }; }
            var _this = this;
            this.object = object;
            this.type = type;
            this._options = _options;
            this._scene = _scene;
            this._bodyUpdateRequired = false;
            this._onBeforePhysicsStepCallbacks = new Array();
            this._onAfterPhysicsStepCallbacks = new Array();
            this._onPhysicsCollideCallbacks = [];
            this._deltaPosition = BABYLON.Vector3.Zero();
            this._isDisposed = false;
            //temp variables for parent rotation calculations
            //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
            this._tmpQuat = new BABYLON.Quaternion();
            this._tmpQuat2 = new BABYLON.Quaternion();
            /**
             * this function is executed by the physics engine.
             */
            this.beforeStep = function () {
                if (!_this._physicsEngine) {
                    return;
                }
                _this.object.translate(_this._deltaPosition, -1);
                _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
                _this.object.computeWorldMatrix(false);
                if (_this.object.parent && _this.object.rotationQuaternion) {
                    _this.getParentsRotation();
                    _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
                }
                else {
                    _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
                }
                if (!_this._options.disableBidirectionalTransformation) {
                    _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
                }
                _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
                    func(_this);
                });
            };
            /**
             * this function is executed by the physics engine
             */
            this.afterStep = function () {
                if (!_this._physicsEngine) {
                    return;
                }
                _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
                    func(_this);
                });
                _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
                // object has now its world rotation. needs to be converted to local.
                if (_this.object.parent && _this.object.rotationQuaternion) {
                    _this.getParentsRotation();
                    _this._tmpQuat.conjugateInPlace();
                    _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
                }
                // take the position set and make it the absolute position of this object.
                _this.object.setAbsolutePosition(_this.object.position);
                _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
                _this.object.translate(_this._deltaPosition, 1);
            };
            /**
             * Legacy collision detection event support
             */
            this.onCollideEvent = null;
            /**
             * event and body object due to cannon's event-based architecture.
             */
            this.onCollide = function (e) {
                if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
                    return;
                }
                if (!_this._physicsEngine) {
                    return;
                }
                var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
                if (otherImpostor) {
                    // Legacy collision detection event support
                    if (_this.onCollideEvent) {
                        _this.onCollideEvent(_this, otherImpostor);
                    }
                    _this._onPhysicsCollideCallbacks.filter(function (obj) {
                        return obj.otherImpostors.indexOf(otherImpostor) !== -1;
                    }).forEach(function (obj) {
                        obj.callback(_this, otherImpostor);
                    });
                }
            };
            //sanity check!
            if (!this.object) {
                BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
                return;
            }
            //legacy support for old syntax.
            if (!this._scene && object.getScene) {
                this._scene = object.getScene();
            }
            if (!this._scene) {
                return;
            }
            this._physicsEngine = this._scene.getPhysicsEngine();
            if (!this._physicsEngine) {
                BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
            }
            else {
                //set the object's quaternion, if not set
                if (!this.object.rotationQuaternion) {
                    if (this.object.rotation) {
                        this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
                    }
                    else {
                        this.object.rotationQuaternion = new BABYLON.Quaternion();
                    }
                }
                //default options params
                this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
                this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
                this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
                this._joints = [];
                //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
                if (!this.object.parent || this._options.ignoreParent) {
                    this._init();
                }
                else if (this.object.parent.physicsImpostor) {
                    BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
                }
            }
        }
        Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
            /**
             * Specifies if the physics imposter is disposed
             */
            get: function () {
                return this._isDisposed;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsImpostor.prototype, "mass", {
            /**
             * Gets the mass of the physics imposter
             */
            get: function () {
                return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
            },
            set: function (value) {
                this.setMass(value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsImpostor.prototype, "friction", {
            /**
             * Gets the coefficient of friction
             */
            get: function () {
                return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
            },
            /**
             * Sets the coefficient of friction
             */
            set: function (value) {
                if (!this._physicsEngine) {
                    return;
                }
                this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
            /**
             * Gets the coefficient of restitution
             */
            get: function () {
                return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
            },
            /**
             * Sets the coefficient of restitution
             */
            set: function (value) {
                if (!this._physicsEngine) {
                    return;
                }
                this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * This function will completly initialize this impostor.
         * It will create a new body - but only if this mesh has no parent.
         * If it has, this impostor will not be used other than to define the impostor
         * of the child mesh.
         * @hidden
         */
        PhysicsImpostor.prototype._init = function () {
            if (!this._physicsEngine) {
                return;
            }
            this._physicsEngine.removeImpostor(this);
            this.physicsBody = null;
            this._parent = this._parent || this._getPhysicsParent();
            if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
                this._physicsEngine.addImpostor(this);
            }
        };
        PhysicsImpostor.prototype._getPhysicsParent = function () {
            if (this.object.parent instanceof BABYLON.AbstractMesh) {
                var parentMesh = this.object.parent;
                return parentMesh.physicsImpostor;
            }
            return null;
        };
        /**
         * Should a new body be generated.
         * @returns boolean specifying if body initialization is required
         */
        PhysicsImpostor.prototype.isBodyInitRequired = function () {
            return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
        };
        /**
         * Sets the updated scaling
         * @param updated Specifies if the scaling is updated
         */
        PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
            this.forceUpdate();
        };
        /**
         * Force a regeneration of this or the parent's impostor's body.
         * Use under cautious - This will remove all joints already implemented.
         */
        PhysicsImpostor.prototype.forceUpdate = function () {
            this._init();
            if (this.parent && !this._options.ignoreParent) {
                this.parent.forceUpdate();
            }
        };
        Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
            /*public get mesh(): AbstractMesh {
                return this._mesh;
            }*/
            /**
             * Gets the body that holds this impostor. Either its own, or its parent.
             */
            get: function () {
                return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
            },
            /**
             * Set the physics body. Used mainly by the physics engine/plugin
             */
            set: function (physicsBody) {
                if (this._physicsBody && this._physicsEngine) {
                    this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
                }
                this._physicsBody = physicsBody;
                this.resetUpdateFlags();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhysicsImpostor.prototype, "parent", {
            /**
             * Get the parent of the physics imposter
             * @returns Physics imposter or null
             */
            get: function () {
                return !this._options.ignoreParent && this._parent ? this._parent : null;
            },
            /**
             * Sets the parent of the physics imposter
             */
            set: function (value) {
                this._parent = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Resets the update flags
         */
        PhysicsImpostor.prototype.resetUpdateFlags = function () {
            this._bodyUpdateRequired = false;
        };
        /**
         * Gets the object extend size
         * @returns the object extend size
         */
        PhysicsImpostor.prototype.getObjectExtendSize = function () {
            if (this.object.getBoundingInfo) {
                var q = this.object.rotationQuaternion;
                //reset rotation
                this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
                //calculate the world matrix with no rotation
                this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
                var boundingInfo = this.object.getBoundingInfo();
                var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
                //bring back the rotation
                this.object.rotationQuaternion = q;
                //calculate the world matrix with the new rotation
                this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
                return size;
            }
            else {
                return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
            }
        };
        /**
         * Gets the object center
         * @returns The object center
         */
        PhysicsImpostor.prototype.getObjectCenter = function () {
            if (this.object.getBoundingInfo) {
                var boundingInfo = this.object.getBoundingInfo();
                return boundingInfo.boundingBox.centerWorld;
            }
            else {
                return this.object.position;
            }
        };
        /**
         * Get a specific parametes from the options parameter
         * @param paramName The object parameter name
         * @returns The object parameter
         */
        PhysicsImpostor.prototype.getParam = function (paramName) {
            return this._options[paramName];
        };
        /**
         * Sets a specific parameter in the options given to the physics plugin
         * @param paramName The parameter name
         * @param value The value of the parameter
         */
        PhysicsImpostor.prototype.setParam = function (paramName, value) {
            this._options[paramName] = value;
            this._bodyUpdateRequired = true;
        };
        /**
         * Specifically change the body's mass option. Won't recreate the physics body object
         * @param mass The mass of the physics imposter
         */
        PhysicsImpostor.prototype.setMass = function (mass) {
            if (this.getParam("mass") !== mass) {
                this.setParam("mass", mass);
            }
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
            }
        };
        /**
         * Gets the linear velocity
         * @returns  linear velocity or null
         */
        PhysicsImpostor.prototype.getLinearVelocity = function () {
            return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
        };
        /**
         * Sets the linear velocity
         * @param velocity  linear velocity or null
         */
        PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
            }
        };
        /**
         * Gets the angular velocity
         * @returns angular velocity or null
         */
        PhysicsImpostor.prototype.getAngularVelocity = function () {
            return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
        };
        /**
         * Sets the angular velocity
         * @param velocity The velocity or null
         */
        PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
            }
        };
        /**
         * Execute a function with the physics plugin native code
         * Provide a function the will have two variables - the world object and the physics body object
         * @param func The function to execute with the physics plugin native code
         */
        PhysicsImpostor.prototype.executeNativeFunction = function (func) {
            if (this._physicsEngine) {
                func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
            }
        };
        /**
         * Register a function that will be executed before the physics world is stepping forward
         * @param func The function to execute before the physics world is stepped forward
         */
        PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
            this._onBeforePhysicsStepCallbacks.push(func);
        };
        /**
         * Unregister a function that will be executed before the physics world is stepping forward
         * @param func The function to execute before the physics world is stepped forward
         */
        PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
            var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
            if (index > -1) {
                this._onBeforePhysicsStepCallbacks.splice(index, 1);
            }
            else {
                BABYLON.Tools.Warn("Function to remove was not found");
            }
        };
        /**
         * Register a function that will be executed after the physics step
         * @param func The function to execute after physics step
         */
        PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
            this._onAfterPhysicsStepCallbacks.push(func);
        };
        /**
         * Unregisters a function that will be executed after the physics step
         * @param func The function to execute after physics step
         */
        PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
            var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
            if (index > -1) {
                this._onAfterPhysicsStepCallbacks.splice(index, 1);
            }
            else {
                BABYLON.Tools.Warn("Function to remove was not found");
            }
        };
        /**
         * register a function that will be executed when this impostor collides against a different body
         * @param collideAgainst Physics imposter, or array of physics imposters to collide against
         * @param func Callback that is executed on collision
         */
        PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
            var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
            this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
        };
        /**
         * Unregisters the physics imposter on contact
         * @param collideAgainst The physics object to collide against
         * @param func Callback to execute on collision
         */
        PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
            var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
            var index = -1;
            var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
                if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
                    // chcek the arrays match
                    var sameList = cbDef.otherImpostors.every(function (impostor) {
                        return collidedAgainstList.indexOf(impostor) > -1;
                    });
                    if (sameList) {
                        index = idx;
                    }
                    return sameList;
                }
                return false;
            });
            if (found) {
                this._onPhysicsCollideCallbacks.splice(index, 1);
            }
            else {
                BABYLON.Tools.Warn("Function to remove was not found");
            }
        };
        /**
         * Get the parent rotation
         * @returns The parent rotation
         */
        PhysicsImpostor.prototype.getParentsRotation = function () {
            var parent = this.object.parent;
            this._tmpQuat.copyFromFloats(0, 0, 0, 1);
            while (parent) {
                if (parent.rotationQuaternion) {
                    this._tmpQuat2.copyFrom(parent.rotationQuaternion);
                }
                else {
                    BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
                }
                this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
                parent = parent.parent;
            }
            return this._tmpQuat;
        };
        /**
         * Apply a force
         * @param force The force to apply
         * @param contactPoint The contact point for the force
         * @returns The physics imposter
         */
        PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
            }
            return this;
        };
        /**
         * Apply an impulse
         * @param force The impulse force
         * @param contactPoint The contact point for the impulse force
         * @returns The physics imposter
         */
        PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
            }
            return this;
        };
        /**
         * A help function to create a joint
         * @param otherImpostor A physics imposter used to create a joint
         * @param jointType The type of joint
         * @param jointData The data for the joint
         * @returns The physics imposter
         */
        PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
            var joint = new BABYLON.PhysicsJoint(jointType, jointData);
            this.addJoint(otherImpostor, joint);
            return this;
        };
        /**
         * Add a joint to this impostor with a different impostor
         * @param otherImpostor A physics imposter used to add a joint
         * @param joint The joint to add
         * @returns The physics imposter
         */
        PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
            this._joints.push({
                otherImpostor: otherImpostor,
                joint: joint
            });
            if (this._physicsEngine) {
                this._physicsEngine.addJoint(this, otherImpostor, joint);
            }
            return this;
        };
        /**
         * Will keep this body still, in a sleep mode.
         * @returns the physics imposter
         */
        PhysicsImpostor.prototype.sleep = function () {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().sleepBody(this);
            }
            return this;
        };
        /**
         * Wake the body up.
         * @returns The physics imposter
         */
        PhysicsImpostor.prototype.wakeUp = function () {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
            }
            return this;
        };
        /**
         * Clones the physics imposter
         * @param newObject The physics imposter clones to this physics-enabled object
         * @returns A nullable physics imposter
         */
        PhysicsImpostor.prototype.clone = function (newObject) {
            if (!newObject) {
                return null;
            }
            return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
        };
        /**
         * Disposes the physics imposter
         */
        PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
            var _this = this;
            //no dispose if no physics engine is available.
            if (!this._physicsEngine) {
                return;
            }
            this._joints.forEach(function (j) {
                if (_this._physicsEngine) {
                    _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
                }
            });
            //dispose the physics body
            this._physicsEngine.removeImpostor(this);
            if (this.parent) {
                this.parent.forceUpdate();
            }
            else {
                /*this._object.getChildMeshes().forEach(function(mesh) {
                    if (mesh.physicsImpostor) {
                        if (disposeChildren) {
                            mesh.physicsImpostor.dispose();
                            mesh.physicsImpostor = null;
                        }
                    }
                })*/
            }
            this._isDisposed = true;
        };
        /**
         * Sets the delta position
         * @param position The delta position amount
         */
        PhysicsImpostor.prototype.setDeltaPosition = function (position) {
            this._deltaPosition.copyFrom(position);
        };
        /**
         * Sets the delta rotation
         * @param rotation The delta rotation amount
         */
        PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
            if (!this._deltaRotation) {
                this._deltaRotation = new BABYLON.Quaternion();
            }
            this._deltaRotation.copyFrom(rotation);
            this._deltaRotationConjugated = this._deltaRotation.conjugate();
        };
        /**
         * Gets the box size of the physics imposter and stores the result in the input parameter
         * @param result Stores the box size
         * @returns The physics imposter
         */
        PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
            if (this._physicsEngine) {
                this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
            }
            return this;
        };
        /**
         * Gets the radius of the physics imposter
         * @returns Radius of the physics imposter
         */
        PhysicsImpostor.prototype.getRadius = function () {
            return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
        };
        /**
         * Sync a bone with this impostor
         * @param bone The bone to sync to the impostor.
         * @param boneMesh The mesh that the bone is influencing.
         * @param jointPivot The pivot of the joint / bone in local space.
         * @param distToJoint Optional distance from the impostor to the joint.
         * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
         */
        PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
            var tempVec = PhysicsImpostor._tmpVecs[0];
            var mesh = this.object;
            if (mesh.rotationQuaternion) {
                if (adjustRotation) {
                    var tempQuat = PhysicsImpostor._tmpQuat;
                    mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
                    bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
                }
                else {
                    bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
                }
            }
            tempVec.x = 0;
            tempVec.y = 0;
            tempVec.z = 0;
            if (jointPivot) {
                tempVec.x = jointPivot.x;
                tempVec.y = jointPivot.y;
                tempVec.z = jointPivot.z;
                bone.getDirectionToRef(tempVec, boneMesh, tempVec);
                if (distToJoint === undefined || distToJoint === null) {
                    distToJoint = jointPivot.length();
                }
                tempVec.x *= distToJoint;
                tempVec.y *= distToJoint;
                tempVec.z *= distToJoint;
            }
            if (bone.getParent()) {
                tempVec.addInPlace(mesh.getAbsolutePosition());
                bone.setAbsolutePosition(tempVec, boneMesh);
            }
            else {
                boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
                boneMesh.position.x -= tempVec.x;
                boneMesh.position.y -= tempVec.y;
                boneMesh.position.z -= tempVec.z;
            }
        };
        /**
         * Sync impostor to a bone
         * @param bone The bone that the impostor will be synced to.
         * @param boneMesh The mesh that the bone is influencing.
         * @param jointPivot The pivot of the joint / bone in local space.
         * @param distToJoint Optional distance from the impostor to the joint.
         * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
         * @param boneAxis Optional vector3 axis the bone is aligned with
         */
        PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
            var mesh = this.object;
            if (mesh.rotationQuaternion) {
                if (adjustRotation) {
                    var tempQuat = PhysicsImpostor._tmpQuat;
                    bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
                    tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
                }
                else {
                    bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
                }
            }
            var pos = PhysicsImpostor._tmpVecs[0];
            var boneDir = PhysicsImpostor._tmpVecs[1];
            if (!boneAxis) {
                boneAxis = PhysicsImpostor._tmpVecs[2];
                boneAxis.x = 0;
                boneAxis.y = 1;
                boneAxis.z = 0;
            }
            bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
            bone.getAbsolutePositionToRef(boneMesh, pos);
            if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
                distToJoint = jointPivot.length();
            }
            if (distToJoint !== undefined && distToJoint !== null) {
                pos.x += boneDir.x * distToJoint;
                pos.y += boneDir.y * distToJoint;
                pos.z += boneDir.z * distToJoint;
            }
            mesh.setAbsolutePosition(pos);
        };
        /**
         * The default object size of the imposter
         */
        PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
        /**
         * The identity quaternion of the imposter
         */
        PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
        PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
        PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
        //Impostor types
        /**
         * No-Imposter type
         */
        PhysicsImpostor.NoImpostor = 0;
        /**
         * Sphere-Imposter type
         */
        PhysicsImpostor.SphereImpostor = 1;
        /**
         * Box-Imposter type
         */
        PhysicsImpostor.BoxImpostor = 2;
        /**
         * Plane-Imposter type
         */
        PhysicsImpostor.PlaneImpostor = 3;
        /**
         * Mesh-imposter type
         */
        PhysicsImpostor.MeshImpostor = 4;
        /**
         * Cylinder-Imposter type
         */
        PhysicsImpostor.CylinderImpostor = 7;
        /**
         * Particle-Imposter type
         */
        PhysicsImpostor.ParticleImpostor = 8;
        /**
         * Heightmap-Imposter type
         */
        PhysicsImpostor.HeightmapImpostor = 9;
        return PhysicsImpostor;
    }());
    BABYLON.PhysicsImpostor = PhysicsImpostor;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.physicsImpostor.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to control physics engine
     * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsEngine = /** @class */ (function () {
        /**
         * Creates a new Physics Engine
         * @param gravity defines the gravity vector used by the simulation
         * @param _physicsPlugin defines the plugin to use (CannonJS by default)
         */
        function PhysicsEngine(gravity, _physicsPlugin) {
            if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
            this._physicsPlugin = _physicsPlugin;
            this._impostors = [];
            this._joints = [];
            if (!this._physicsPlugin.isSupported()) {
                throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
                    + "Please make sure it is included.");
            }
            gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
            this.setGravity(gravity);
            this.setTimeStep();
        }
        /**
         * Sets the gravity vector used by the simulation
         * @param gravity defines the gravity vector to use
         */
        PhysicsEngine.prototype.setGravity = function (gravity) {
            this.gravity = gravity;
            this._physicsPlugin.setGravity(this.gravity);
        };
        /**
         * Set the time step of the physics engine.
         * Default is 1/60.
         * To slow it down, enter 1/600 for example.
         * To speed it up, 1/30
         * @param newTimeStep defines the new timestep to apply to this world.
         */
        PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
            if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
            this._physicsPlugin.setTimeStep(newTimeStep);
        };
        /**
         * Get the time step of the physics engine.
         * @returns the current time step
         */
        PhysicsEngine.prototype.getTimeStep = function () {
            return this._physicsPlugin.getTimeStep();
        };
        /**
         * Release all resources
         */
        PhysicsEngine.prototype.dispose = function () {
            this._impostors.forEach(function (impostor) {
                impostor.dispose();
            });
            this._physicsPlugin.dispose();
        };
        /**
         * Gets the name of the current physics plugin
         * @returns the name of the plugin
         */
        PhysicsEngine.prototype.getPhysicsPluginName = function () {
            return this._physicsPlugin.name;
        };
        /**
         * Adding a new impostor for the impostor tracking.
         * This will be done by the impostor itself.
         * @param impostor the impostor to add
         */
        PhysicsEngine.prototype.addImpostor = function (impostor) {
            impostor.uniqueId = this._impostors.push(impostor);
            //if no parent, generate the body
            if (!impostor.parent) {
                this._physicsPlugin.generatePhysicsBody(impostor);
            }
        };
        /**
         * Remove an impostor from the engine.
         * This impostor and its mesh will not longer be updated by the physics engine.
         * @param impostor the impostor to remove
         */
        PhysicsEngine.prototype.removeImpostor = function (impostor) {
            var index = this._impostors.indexOf(impostor);
            if (index > -1) {
                var removed = this._impostors.splice(index, 1);
                //Is it needed?
                if (removed.length) {
                    //this will also remove it from the world.
                    removed[0].physicsBody = null;
                }
            }
        };
        /**
         * Add a joint to the physics engine
         * @param mainImpostor defines the main impostor to which the joint is added.
         * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
         * @param joint defines the joint that will connect both impostors.
         */
        PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
            var impostorJoint = {
                mainImpostor: mainImpostor,
                connectedImpostor: connectedImpostor,
                joint: joint
            };
            joint.physicsPlugin = this._physicsPlugin;
            this._joints.push(impostorJoint);
            this._physicsPlugin.generateJoint(impostorJoint);
        };
        /**
         * Removes a joint from the simulation
         * @param mainImpostor defines the impostor used with the joint
         * @param connectedImpostor defines the other impostor connected to the main one by the joint
         * @param joint defines the joint to remove
         */
        PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
            var matchingJoints = this._joints.filter(function (impostorJoint) {
                return (impostorJoint.connectedImpostor === connectedImpostor
                    && impostorJoint.joint === joint
                    && impostorJoint.mainImpostor === mainImpostor);
            });
            if (matchingJoints.length) {
                this._physicsPlugin.removeJoint(matchingJoints[0]);
                //TODO remove it from the list as well
            }
        };
        /**
         * Called by the scene. No need to call it.
         * @param delta defines the timespam between frames
         */
        PhysicsEngine.prototype._step = function (delta) {
            var _this = this;
            //check if any mesh has no body / requires an update
            this._impostors.forEach(function (impostor) {
                if (impostor.isBodyInitRequired()) {
                    _this._physicsPlugin.generatePhysicsBody(impostor);
                }
            });
            if (delta > 0.1) {
                delta = 0.1;
            }
            else if (delta <= 0) {
                delta = 1.0 / 60.0;
            }
            this._physicsPlugin.executeStep(delta, this._impostors);
        };
        /**
         * Gets the current plugin used to run the simulation
         * @returns current plugin
         */
        PhysicsEngine.prototype.getPhysicsPlugin = function () {
            return this._physicsPlugin;
        };
        /**
         * Gets the list of physic impostors
         * @returns an array of PhysicsImpostor
         */
        PhysicsEngine.prototype.getImpostors = function () {
            return this._impostors;
        };
        /**
         * Gets the impostor for a physics enabled object
         * @param object defines the object impersonated by the impostor
         * @returns the PhysicsImpostor or null if not found
         */
        PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
            for (var i = 0; i < this._impostors.length; ++i) {
                if (this._impostors[i].object === object) {
                    return this._impostors[i];
                }
            }
            return null;
        };
        /**
         * Gets the impostor for a physics body object
         * @param body defines physics body used by the impostor
         * @returns the PhysicsImpostor or null if not found
         */
        PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
            for (var i = 0; i < this._impostors.length; ++i) {
                if (this._impostors[i].physicsBody === body) {
                    return this._impostors[i];
                }
            }
            return null;
        };
        /**
         * Global value used to control the smallest number supported by the simulation
         */
        PhysicsEngine.Epsilon = 0.001;
        return PhysicsEngine;
    }());
    BABYLON.PhysicsEngine = PhysicsEngine;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.physicsEngine.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A helper for physics simulations
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsHelper = /** @class */ (function () {
        /**
         * Initializes the Physics helper
         * @param scene Babylon.js scene
         */
        function PhysicsHelper(scene) {
            this._scene = scene;
            this._physicsEngine = this._scene.getPhysicsEngine();
            if (!this._physicsEngine) {
                BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
            }
        }
        /**
         * Applies a radial explosion impulse
         * @param origin the origin of the explosion
         * @param radius the explosion radius
         * @param strength the explosion strength
         * @param falloff possible options: Constant & Linear. Defaults to Constant
         * @returns A physics radial explosion event, or null
         */
        PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
            if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
            if (!this._physicsEngine) {
                BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
                return null;
            }
            var impostors = this._physicsEngine.getImpostors();
            if (impostors.length === 0) {
                return null;
            }
            var event = new PhysicsRadialExplosionEvent(this._scene);
            impostors.forEach(function (impostor) {
                var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
                if (!impostorForceAndContactPoint) {
                    return;
                }
                impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
            });
            event.dispose(false);
            return event;
        };
        /**
         * Applies a radial explosion force
         * @param origin the origin of the explosion
         * @param radius the explosion radius
         * @param strength the explosion strength
         * @param falloff possible options: Constant & Linear. Defaults to Constant
         * @returns A physics radial explosion event, or null
         */
        PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
            if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
            if (!this._physicsEngine) {
                BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
                return null;
            }
            var impostors = this._physicsEngine.getImpostors();
            if (impostors.length === 0) {
                return null;
            }
            var event = new PhysicsRadialExplosionEvent(this._scene);
            impostors.forEach(function (impostor) {
                var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
                if (!impostorForceAndContactPoint) {
                    return;
                }
                impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
            });
            event.dispose(false);
            return event;
        };
        /**
         * Creates a gravitational field
         * @param origin the origin of the explosion
         * @param radius the explosion radius
         * @param strength the explosion strength
         * @param falloff possible options: Constant & Linear. Defaults to Constant
         * @returns A physics gravitational field event, or null
         */
        PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
            if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
            if (!this._physicsEngine) {
                BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
                return null;
            }
            var impostors = this._physicsEngine.getImpostors();
            if (impostors.length === 0) {
                return null;
            }
            var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
            event.dispose(false);
            return event;
        };
        /**
         * Creates a physics updraft event
         * @param origin the origin of the updraft
         * @param radius the radius of the updraft
         * @param strength the strength of the updraft
         * @param height the height of the updraft
         * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
         * @returns A physics updraft event, or null
         */
        PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
            if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
            if (!this._physicsEngine) {
                BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
                return null;
            }
            if (this._physicsEngine.getImpostors().length === 0) {
                return null;
            }
            var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
            event.dispose(false);
            return event;
        };
        /**
         * Creates a physics vortex event
         * @param origin the of the vortex
         * @param radius the radius of the vortex
         * @param strength the strength of the vortex
         * @param height   the height of the vortex
         * @returns a Physics vortex event, or null
         * A physics vortex event or null
         */
        PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
            if (!this._physicsEngine) {
                BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
                return null;
            }
            if (this._physicsEngine.getImpostors().length === 0) {
                return null;
            }
            var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
            event.dispose(false);
            return event;
        };
        return PhysicsHelper;
    }());
    BABYLON.PhysicsHelper = PhysicsHelper;
    /**
     * Represents a physics radial explosion event
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsRadialExplosionEvent = /** @class */ (function () {
        /**
         * Initializes a radial explosioin event
         * @param scene BabylonJS scene
         */
        function PhysicsRadialExplosionEvent(scene) {
            this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
            this._rays = [];
            this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
            this._scene = scene;
        }
        /**
         * Returns the data related to the radial explosion event (sphere & rays).
         * @returns The radial explosion event data
         */
        PhysicsRadialExplosionEvent.prototype.getData = function () {
            this._dataFetched = true;
            return {
                sphere: this._sphere,
                rays: this._rays,
            };
        };
        /**
         * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
         * @param impostor A physics imposter
         * @param origin the origin of the explosion
         * @param radius the explosion radius
         * @param strength the explosion strength
         * @param falloff possible options: Constant & Linear
         * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
         */
        PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
            if (impostor.mass === 0) {
                return null;
            }
            if (!this._intersectsWithSphere(impostor, origin, radius)) {
                return null;
            }
            if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
                return null;
            }
            var impostorObjectCenter = impostor.getObjectCenter();
            var direction = impostorObjectCenter.subtract(origin);
            var ray = new BABYLON.Ray(origin, direction, radius);
            this._rays.push(ray);
            var hit = ray.intersectsMesh(impostor.object);
            var contactPoint = hit.pickedPoint;
            if (!contactPoint) {
                return null;
            }
            var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
            if (distanceFromOrigin > radius) {
                return null;
            }
            var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
                ? strength
                : strength * (1 - (distanceFromOrigin / radius));
            var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
            return { force: force, contactPoint: contactPoint };
        };
        /**
         * Disposes the sphere.
         * @param force Specifies if the sphere should be disposed by force
         */
        PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
            var _this = this;
            if (force === void 0) { force = true; }
            if (force) {
                this._sphere.dispose();
            }
            else {
                setTimeout(function () {
                    if (!_this._dataFetched) {
                        _this._sphere.dispose();
                    }
                }, 0);
            }
        };
        /*** Helpers ***/
        PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
            if (!this._sphere) {
                this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
                this._sphere.isVisible = false;
            }
        };
        PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
            var impostorObject = impostor.object;
            this._prepareSphere();
            this._sphere.position = origin;
            this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
            this._sphere._updateBoundingInfo();
            this._sphere.computeWorldMatrix(true);
            return this._sphere.intersectsMesh(impostorObject, true);
        };
        return PhysicsRadialExplosionEvent;
    }());
    BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
    /**
     * Represents a gravitational field event
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsGravitationalFieldEvent = /** @class */ (function () {
        /**
         * Initializes the physics gravitational field event
         * @param physicsHelper A physics helper
         * @param scene BabylonJS scene
         * @param origin The origin position of the gravitational field event
         * @param radius The radius of the gravitational field event
         * @param strength The strength of the gravitational field event
         * @param falloff The falloff for the gravitational field event
         */
        function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
            if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
            this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
            this._physicsHelper = physicsHelper;
            this._scene = scene;
            this._origin = origin;
            this._radius = radius;
            this._strength = strength;
            this._falloff = falloff;
            this._tickCallback = this._tick.bind(this);
        }
        /**
         * Returns the data related to the gravitational field event (sphere).
         * @returns A gravitational field event
         */
        PhysicsGravitationalFieldEvent.prototype.getData = function () {
            this._dataFetched = true;
            return {
                sphere: this._sphere,
            };
        };
        /**
         * Enables the gravitational field.
         */
        PhysicsGravitationalFieldEvent.prototype.enable = function () {
            this._tickCallback.call(this);
            this._scene.registerBeforeRender(this._tickCallback);
        };
        /**
         * Disables the gravitational field.
         */
        PhysicsGravitationalFieldEvent.prototype.disable = function () {
            this._scene.unregisterBeforeRender(this._tickCallback);
        };
        /**
         * Disposes the sphere.
         * @param force The force to dispose from the gravitational field event
         */
        PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
            var _this = this;
            if (force === void 0) { force = true; }
            if (force) {
                this._sphere.dispose();
            }
            else {
                setTimeout(function () {
                    if (!_this._dataFetched) {
                        _this._sphere.dispose();
                    }
                }, 0);
            }
        };
        PhysicsGravitationalFieldEvent.prototype._tick = function () {
            // Since the params won't change, we fetch the event only once
            if (this._sphere) {
                this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
            }
            else {
                var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
                if (radialExplosionEvent) {
                    this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
                }
            }
        };
        return PhysicsGravitationalFieldEvent;
    }());
    BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
    /**
     * Represents a physics updraft event
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsUpdraftEvent = /** @class */ (function () {
        /**
         * Initializes the physics updraft event
         * @param _scene BabylonJS scene
         * @param _origin The origin position of the updraft
         * @param _radius The radius of the updraft
         * @param _strength The strength of the updraft
         * @param _height The height of the updraft
         * @param _updraftMode The mode of the updraft
         */
        function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
            this._scene = _scene;
            this._origin = _origin;
            this._radius = _radius;
            this._strength = _strength;
            this._height = _height;
            this._updraftMode = _updraftMode;
            this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
            this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
            this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
            this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
            this._physicsEngine = this._scene.getPhysicsEngine();
            this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
            this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
            if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
                this._originDirection = this._origin.subtract(this._originTop).normalize();
            }
            this._tickCallback = this._tick.bind(this);
        }
        /**
         * Returns the data related to the updraft event (cylinder).
         * @returns A physics updraft event
         */
        PhysicsUpdraftEvent.prototype.getData = function () {
            this._dataFetched = true;
            return {
                cylinder: this._cylinder,
            };
        };
        /**
         * Enables the updraft.
         */
        PhysicsUpdraftEvent.prototype.enable = function () {
            this._tickCallback.call(this);
            this._scene.registerBeforeRender(this._tickCallback);
        };
        /**
         * Disables the cortex.
         */
        PhysicsUpdraftEvent.prototype.disable = function () {
            this._scene.unregisterBeforeRender(this._tickCallback);
        };
        /**
         * Disposes the sphere.
         * @param force Specifies if the updraft should be disposed by force
         */
        PhysicsUpdraftEvent.prototype.dispose = function (force) {
            var _this = this;
            if (force === void 0) { force = true; }
            if (force) {
                this._cylinder.dispose();
            }
            else {
                setTimeout(function () {
                    if (!_this._dataFetched) {
                        _this._cylinder.dispose();
                    }
                }, 0);
            }
        };
        PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
            if (impostor.mass === 0) {
                return null;
            }
            if (!this._intersectsWithCylinder(impostor)) {
                return null;
            }
            var impostorObjectCenter = impostor.getObjectCenter();
            if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
                var direction = this._originDirection;
            }
            else {
                var direction = impostorObjectCenter.subtract(this._originTop);
            }
            var multiplier = this._strength * -1;
            var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
            return { force: force, contactPoint: impostorObjectCenter };
        };
        PhysicsUpdraftEvent.prototype._tick = function () {
            var _this = this;
            this._physicsEngine.getImpostors().forEach(function (impostor) {
                var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
                if (!impostorForceAndContactPoint) {
                    return;
                }
                impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
            });
        };
        /*** Helpers ***/
        PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
            if (!this._cylinder) {
                this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
                    height: this._height,
                    diameter: this._radius * 2,
                }, this._scene);
                this._cylinder.isVisible = false;
            }
        };
        PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
            var impostorObject = impostor.object;
            this._prepareCylinder();
            this._cylinder.position = this._cylinderPosition;
            return this._cylinder.intersectsMesh(impostorObject, true);
        };
        return PhysicsUpdraftEvent;
    }());
    BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
    /**
     * Represents a physics vortex event
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsVortexEvent = /** @class */ (function () {
        /**
         * Initializes the physics vortex event
         * @param _scene The BabylonJS scene
         * @param _origin The origin position of the vortex
         * @param _radius The radius of the vortex
         * @param _strength The strength of the vortex
         * @param _height The height of the vortex
         */
        function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
            this._scene = _scene;
            this._origin = _origin;
            this._radius = _radius;
            this._strength = _strength;
            this._height = _height;
            this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
            this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
            this._updraftMultiplier = 0.02;
            this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
            this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
            this._physicsEngine = this._scene.getPhysicsEngine();
            this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
            this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
            this._tickCallback = this._tick.bind(this);
        }
        /**
         * Returns the data related to the vortex event (cylinder).
         * @returns The physics vortex event data
         */
        PhysicsVortexEvent.prototype.getData = function () {
            this._dataFetched = true;
            return {
                cylinder: this._cylinder,
            };
        };
        /**
         * Enables the vortex.
         */
        PhysicsVortexEvent.prototype.enable = function () {
            this._tickCallback.call(this);
            this._scene.registerBeforeRender(this._tickCallback);
        };
        /**
         * Disables the cortex.
         */
        PhysicsVortexEvent.prototype.disable = function () {
            this._scene.unregisterBeforeRender(this._tickCallback);
        };
        /**
         * Disposes the sphere.
         * @param force
         */
        PhysicsVortexEvent.prototype.dispose = function (force) {
            var _this = this;
            if (force === void 0) { force = true; }
            if (force) {
                this._cylinder.dispose();
            }
            else {
                setTimeout(function () {
                    if (!_this._dataFetched) {
                        _this._cylinder.dispose();
                    }
                }, 0);
            }
        };
        PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
            if (impostor.mass === 0) {
                return null;
            }
            if (!this._intersectsWithCylinder(impostor)) {
                return null;
            }
            if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
                return null;
            }
            var impostorObjectCenter = impostor.getObjectCenter();
            var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
            var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
            var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
            var hit = ray.intersectsMesh(impostor.object);
            var contactPoint = hit.pickedPoint;
            if (!contactPoint) {
                return null;
            }
            var absoluteDistanceFromOrigin = hit.distance / this._radius;
            var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
            var directionToOrigin = contactPoint.normalize();
            if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
                directionToOrigin = directionToOrigin.negate();
            }
            // TODO: find a more physically based solution
            if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
                var forceX = directionToOrigin.x * this._strength / 8;
                var forceY = directionToOrigin.y * this._updraftMultiplier;
                var forceZ = directionToOrigin.z * this._strength / 8;
            }
            else {
                var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
                var forceY = this._originTop.y * this._updraftMultiplier;
                var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
            }
            var force = new BABYLON.Vector3(forceX, forceY, forceZ);
            force = force.multiplyByFloats(this._strength, this._strength, this._strength);
            return { force: force, contactPoint: impostorObjectCenter };
        };
        PhysicsVortexEvent.prototype._tick = function () {
            var _this = this;
            this._physicsEngine.getImpostors().forEach(function (impostor) {
                var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
                if (!impostorForceAndContactPoint) {
                    return;
                }
                impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
            });
        };
        /*** Helpers ***/
        PhysicsVortexEvent.prototype._prepareCylinder = function () {
            if (!this._cylinder) {
                this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
                    height: this._height,
                    diameter: this._radius * 2,
                }, this._scene);
                this._cylinder.isVisible = false;
            }
        };
        PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
            var impostorObject = impostor.object;
            this._prepareCylinder();
            this._cylinder.position = this._cylinderPosition;
            return this._cylinder.intersectsMesh(impostorObject, true);
        };
        return PhysicsVortexEvent;
    }());
    BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
    /**
    * The strenght of the force in correspondence to the distance of the affected object
    * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
    */
    var PhysicsRadialImpulseFalloff;
    (function (PhysicsRadialImpulseFalloff) {
        /** Defines that impulse is constant in strength across it's whole radius */
        PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
        /** DEfines that impulse gets weaker if it's further from the origin */
        PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
    })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
    /**
     * The strength of the force in correspondence to the distance of the affected object
     * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    var PhysicsUpdraftMode;
    (function (PhysicsUpdraftMode) {
        /** Defines that the upstream forces will pull towards the top center of the cylinder */
        PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
        /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
        PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
    })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.physicsHelper.js.map

var BABYLON;
(function (BABYLON) {
    /** @hidden */
    var CannonJSPlugin = /** @class */ (function () {
        function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
            if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
            if (iterations === void 0) { iterations = 10; }
            this._useDeltaForWorldStep = _useDeltaForWorldStep;
            this.name = "CannonJSPlugin";
            this._physicsMaterials = new Array();
            this._fixedTimeStep = 1 / 60;
            //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
            this.BJSCANNON = CANNON;
            this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
            this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
            this._tmpPosition = BABYLON.Vector3.Zero();
            this._tmpDeltaPosition = BABYLON.Vector3.Zero();
            this._tmpUnityRotation = new BABYLON.Quaternion();
            if (!this.isSupported()) {
                BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
                return;
            }
            this._extendNamespace();
            this.world = new this.BJSCANNON.World();
            this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
            this.world.solver.iterations = iterations;
        }
        CannonJSPlugin.prototype.setGravity = function (gravity) {
            this.world.gravity.copy(gravity);
        };
        CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
            this._fixedTimeStep = timeStep;
        };
        CannonJSPlugin.prototype.getTimeStep = function () {
            return this._fixedTimeStep;
        };
        CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
            this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
        };
        CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
            var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
            var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
            impostor.physicsBody.applyImpulse(impulse, worldPoint);
        };
        CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
            var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
            var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
            impostor.physicsBody.applyForce(impulse, worldPoint);
        };
        CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
            //parent-child relationship. Does this impostor has a parent impostor?
            if (impostor.parent) {
                if (impostor.physicsBody) {
                    this.removePhysicsBody(impostor);
                    //TODO is that needed?
                    impostor.forceUpdate();
                }
                return;
            }
            //should a new body be created for this impostor?
            if (impostor.isBodyInitRequired()) {
                var shape = this._createShape(impostor);
                //unregister events, if body is being changed
                var oldBody = impostor.physicsBody;
                if (oldBody) {
                    this.removePhysicsBody(impostor);
                }
                //create the body and material
                var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
                var bodyCreationObject = {
                    mass: impostor.getParam("mass"),
                    material: material
                };
                // A simple extend, in case native options were used.
                var nativeOptions = impostor.getParam("nativeOptions");
                for (var key in nativeOptions) {
                    if (nativeOptions.hasOwnProperty(key)) {
                        bodyCreationObject[key] = nativeOptions[key];
                    }
                }
                impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
                impostor.physicsBody.addEventListener("collide", impostor.onCollide);
                this.world.addEventListener("preStep", impostor.beforeStep);
                this.world.addEventListener("postStep", impostor.afterStep);
                impostor.physicsBody.addShape(shape);
                this.world.add(impostor.physicsBody);
                //try to keep the body moving in the right direction by taking old properties.
                //Should be tested!
                if (oldBody) {
                    ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
                        impostor.physicsBody[param].copy(oldBody[param]);
                    });
                }
                this._processChildMeshes(impostor);
            }
            //now update the body's transformation
            this._updatePhysicsBodyTransformation(impostor);
        };
        CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
            var _this = this;
            var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
            var currentRotation = mainImpostor.object.rotationQuaternion;
            if (meshChildren.length) {
                var processMesh = function (localPosition, mesh) {
                    if (!currentRotation || !mesh.rotationQuaternion) {
                        return;
                    }
                    var childImpostor = mesh.getPhysicsImpostor();
                    if (childImpostor) {
                        var parent = childImpostor.parent;
                        if (parent !== mainImpostor) {
                            var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
                            var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
                            if (childImpostor.physicsBody) {
                                _this.removePhysicsBody(childImpostor);
                                childImpostor.physicsBody = null;
                            }
                            childImpostor.parent = mainImpostor;
                            childImpostor.resetUpdateFlags();
                            mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new _this.BJSCANNON.Vec3(pPosition.x, pPosition.y, pPosition.z), new _this.BJSCANNON.Quaternion(localRotation.x, localRotation.y, localRotation.z, localRotation.w));
                            //Add the mass of the children.
                            mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
                        }
                    }
                    currentRotation.multiplyInPlace(mesh.rotationQuaternion);
                    mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
                };
                meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
            }
        };
        CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
            impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
            this.world.removeEventListener("preStep", impostor.beforeStep);
            this.world.removeEventListener("postStep", impostor.afterStep);
            this.world.remove(impostor.physicsBody);
        };
        CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
            var mainBody = impostorJoint.mainImpostor.physicsBody;
            var connectedBody = impostorJoint.connectedImpostor.physicsBody;
            if (!mainBody || !connectedBody) {
                return;
            }
            var constraint;
            var jointData = impostorJoint.joint.jointData;
            //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
            var constraintData = {
                pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
                pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
                axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
                axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
                maxForce: jointData.nativeParams.maxForce,
                collideConnected: !!jointData.collision
            };
            switch (impostorJoint.joint.type) {
                case BABYLON.PhysicsJoint.HingeJoint:
                case BABYLON.PhysicsJoint.Hinge2Joint:
                    constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
                    break;
                case BABYLON.PhysicsJoint.DistanceJoint:
                    constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
                    break;
                case BABYLON.PhysicsJoint.SpringJoint:
                    var springData = jointData;
                    constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
                        restLength: springData.length,
                        stiffness: springData.stiffness,
                        damping: springData.damping,
                        localAnchorA: constraintData.pivotA,
                        localAnchorB: constraintData.pivotB
                    });
                    break;
                case BABYLON.PhysicsJoint.LockJoint:
                    constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
                    break;
                case BABYLON.PhysicsJoint.PointToPointJoint:
                case BABYLON.PhysicsJoint.BallAndSocketJoint:
                default:
                    constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
                    break;
            }
            //set the collideConnected flag after the creation, since DistanceJoint ignores it.
            constraint.collideConnected = !!jointData.collision;
            impostorJoint.joint.physicsJoint = constraint;
            //don't add spring as constraint, as it is not one.
            if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
                this.world.addConstraint(constraint);
            }
            else {
                impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
                    constraint.applyForce();
                };
                impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
            }
        };
        CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
            if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
                this.world.removeConstraint(impostorJoint.joint.physicsJoint);
            }
            else {
                impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
            }
        };
        CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
            var index;
            var mat;
            for (index = 0; index < this._physicsMaterials.length; index++) {
                mat = this._physicsMaterials[index];
                if (mat.friction === friction && mat.restitution === restitution) {
                    return mat;
                }
            }
            var currentMat = new this.BJSCANNON.Material(name);
            currentMat.friction = friction;
            currentMat.restitution = restitution;
            this._physicsMaterials.push(currentMat);
            return currentMat;
        };
        CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
            return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
        };
        CannonJSPlugin.prototype._createShape = function (impostor) {
            var object = impostor.object;
            var returnValue;
            var extendSize = impostor.getObjectExtendSize();
            switch (impostor.type) {
                case BABYLON.PhysicsImpostor.SphereImpostor:
                    var radiusX = extendSize.x;
                    var radiusY = extendSize.y;
                    var radiusZ = extendSize.z;
                    returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
                    break;
                //TMP also for cylinder - TODO Cannon supports cylinder natively.
                case BABYLON.PhysicsImpostor.CylinderImpostor:
                    returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
                    break;
                case BABYLON.PhysicsImpostor.BoxImpostor:
                    var box = extendSize.scale(0.5);
                    returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
                    break;
                case BABYLON.PhysicsImpostor.PlaneImpostor:
                    BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
                    returnValue = new this.BJSCANNON.Plane();
                    break;
                case BABYLON.PhysicsImpostor.MeshImpostor:
                    // should transform the vertex data to world coordinates!!
                    var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
                    var rawFaces = object.getIndices ? object.getIndices() : [];
                    if (!rawVerts) {
                        return;
                    }
                    // get only scale! so the object could transform correctly.
                    var oldPosition = object.position.clone();
                    var oldRotation = object.rotation && object.rotation.clone();
                    var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
                    object.position.copyFromFloats(0, 0, 0);
                    object.rotation && object.rotation.copyFromFloats(0, 0, 0);
                    object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
                    object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
                    var transform = object.computeWorldMatrix(true);
                    // convert rawVerts to object space
                    var temp = new Array();
                    var index;
                    for (index = 0; index < rawVerts.length; index += 3) {
                        BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
                    }
                    BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
                    returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
                    //now set back the transformation!
                    object.position.copyFrom(oldPosition);
                    oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
                    oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
                    break;
                case BABYLON.PhysicsImpostor.HeightmapImpostor:
                    var oldPosition2 = object.position.clone();
                    var oldRotation2 = object.rotation && object.rotation.clone();
                    var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
                    object.position.copyFromFloats(0, 0, 0);
                    object.rotation && object.rotation.copyFromFloats(0, 0, 0);
                    object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
                    object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
                    object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
                    returnValue = this._createHeightmap(object);
                    object.position.copyFrom(oldPosition2);
                    oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
                    oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
                    object.computeWorldMatrix(true);
                    break;
                case BABYLON.PhysicsImpostor.ParticleImpostor:
                    returnValue = new this.BJSCANNON.Particle();
                    break;
            }
            return returnValue;
        };
        CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
            var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
            var transform = object.computeWorldMatrix(true);
            // convert rawVerts to object space
            var temp = new Array();
            var index;
            for (index = 0; index < pos.length; index += 3) {
                BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
            }
            pos = temp;
            var matrix = new Array();
            //For now pointDepth will not be used and will be automatically calculated.
            //Future reference - try and find the best place to add a reference to the pointDepth variable.
            var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
            var boundingInfo = object.getBoundingInfo();
            var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
            var minY = boundingInfo.boundingBox.extendSizeWorld.z;
            var elementSize = dim * 2 / arraySize;
            for (var i = 0; i < pos.length; i = i + 3) {
                var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
                var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
                var y = -pos[i + 2] + minY;
                if (!matrix[x]) {
                    matrix[x] = [];
                }
                if (!matrix[x][z]) {
                    matrix[x][z] = y;
                }
                matrix[x][z] = Math.max(y, matrix[x][z]);
            }
            for (var x = 0; x <= arraySize; ++x) {
                if (!matrix[x]) {
                    var loc = 1;
                    while (!matrix[(x + loc) % arraySize]) {
                        loc++;
                    }
                    matrix[x] = matrix[(x + loc) % arraySize].slice();
                    //console.log("missing x", x);
                }
                for (var z = 0; z <= arraySize; ++z) {
                    if (!matrix[x][z]) {
                        var loc = 1;
                        var newValue;
                        while (newValue === undefined) {
                            newValue = matrix[x][(z + loc++) % arraySize];
                        }
                        matrix[x][z] = newValue;
                    }
                }
            }
            var shape = new this.BJSCANNON.Heightfield(matrix, {
                elementSize: elementSize
            });
            //For future reference, needed for body transformation
            shape.minY = minY;
            return shape;
        };
        CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
            var object = impostor.object;
            //make sure it is updated...
            object.computeWorldMatrix && object.computeWorldMatrix(true);
            // The delta between the mesh position and the mesh bounding box center
            var bInfo = object.getBoundingInfo();
            if (!bInfo) {
                return;
            }
            var center = impostor.getObjectCenter();
            //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
            this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
            this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
            this._tmpPosition.copyFrom(center);
            var quaternion = object.rotationQuaternion;
            if (!quaternion) {
                return;
            }
            //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
            if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
                //-90 DEG in X, precalculated
                quaternion = quaternion.multiply(this._minus90X);
                //Invert! (Precalculated, 90 deg in X)
                //No need to clone. this will never change.
                impostor.setDeltaRotation(this._plus90X);
            }
            //If it is a heightfield, if should be centered.
            if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
                var mesh = object;
                var boundingInfo = mesh.getBoundingInfo();
                //calculate the correct body position:
                var rotationQuaternion = mesh.rotationQuaternion;
                mesh.rotationQuaternion = this._tmpUnityRotation;
                mesh.computeWorldMatrix(true);
                //get original center with no rotation
                var c = center.clone();
                var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
                //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
                var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
                mesh.setPreTransformMatrix(p);
                mesh.computeWorldMatrix(true);
                //calculate the translation
                var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
                this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
                //add it inverted to the delta
                this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
                this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
                //rotation is back
                mesh.rotationQuaternion = rotationQuaternion;
                mesh.setPreTransformMatrix(oldPivot);
                mesh.computeWorldMatrix(true);
            }
            else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
                this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
                //this._tmpPosition.copyFrom(object.position);
            }
            impostor.setDeltaPosition(this._tmpDeltaPosition);
            //Now update the impostor object
            impostor.physicsBody.position.copy(this._tmpPosition);
            impostor.physicsBody.quaternion.copy(quaternion);
        };
        CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
            impostor.object.position.copyFrom(impostor.physicsBody.position);
            if (impostor.object.rotationQuaternion) {
                impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
            }
        };
        CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
            impostor.physicsBody.position.copy(newPosition);
            impostor.physicsBody.quaternion.copy(newRotation);
        };
        CannonJSPlugin.prototype.isSupported = function () {
            return this.BJSCANNON !== undefined;
        };
        CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
            impostor.physicsBody.velocity.copy(velocity);
        };
        CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
            impostor.physicsBody.angularVelocity.copy(velocity);
        };
        CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
            var v = impostor.physicsBody.velocity;
            if (!v) {
                return null;
            }
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
            var v = impostor.physicsBody.angularVelocity;
            if (!v) {
                return null;
            }
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
            impostor.physicsBody.mass = mass;
            impostor.physicsBody.updateMassProperties();
        };
        CannonJSPlugin.prototype.getBodyMass = function (impostor) {
            return impostor.physicsBody.mass;
        };
        CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
            return impostor.physicsBody.material.friction;
        };
        CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
            impostor.physicsBody.material.friction = friction;
        };
        CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
            return impostor.physicsBody.material.restitution;
        };
        CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
            impostor.physicsBody.material.restitution = restitution;
        };
        CannonJSPlugin.prototype.sleepBody = function (impostor) {
            impostor.physicsBody.sleep();
        };
        CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
            impostor.physicsBody.wakeUp();
        };
        CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
            joint.physicsJoint.distance = maxDistance;
        };
        // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
        //     if (!motorIndex) {
        //         joint.physicsJoint.enableMotor();
        //     }
        // }
        // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
        //     if (!motorIndex) {
        //         joint.physicsJoint.disableMotor();
        //     }
        // }
        CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
            if (!motorIndex) {
                joint.physicsJoint.enableMotor();
                joint.physicsJoint.setMotorSpeed(speed);
                if (maxForce) {
                    this.setLimit(joint, maxForce);
                }
            }
        };
        CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
            joint.physicsJoint.motorEquation.maxForce = upperLimit;
            joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
        };
        CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
            var body = impostor.physicsBody;
            mesh.position.x = body.position.x;
            mesh.position.y = body.position.y;
            mesh.position.z = body.position.z;
            if (mesh.rotationQuaternion) {
                mesh.rotationQuaternion.x = body.quaternion.x;
                mesh.rotationQuaternion.y = body.quaternion.y;
                mesh.rotationQuaternion.z = body.quaternion.z;
                mesh.rotationQuaternion.w = body.quaternion.w;
            }
        };
        CannonJSPlugin.prototype.getRadius = function (impostor) {
            var shape = impostor.physicsBody.shapes[0];
            return shape.boundingSphereRadius;
        };
        CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
            var shape = impostor.physicsBody.shapes[0];
            result.x = shape.halfExtents.x * 2;
            result.y = shape.halfExtents.y * 2;
            result.z = shape.halfExtents.z * 2;
        };
        CannonJSPlugin.prototype.dispose = function () {
        };
        CannonJSPlugin.prototype._extendNamespace = function () {
            //this will force cannon to execute at least one step when using interpolation
            var step_tmp1 = new this.BJSCANNON.Vec3();
            var Engine = this.BJSCANNON;
            this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
                maxSubSteps = maxSubSteps || 10;
                timeSinceLastCalled = timeSinceLastCalled || 0;
                if (timeSinceLastCalled === 0) {
                    this.internalStep(dt);
                    this.time += dt;
                }
                else {
                    var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
                    internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
                    var t0 = performance.now();
                    for (var i = 0; i !== internalSteps; i++) {
                        this.internalStep(dt);
                        if (performance.now() - t0 > dt * 1000) {
                            break;
                        }
                    }
                    this.time += timeSinceLastCalled;
                    var h = this.time % dt;
                    var h_div_dt = h / dt;
                    var interpvelo = step_tmp1;
                    var bodies = this.bodies;
                    for (var j = 0; j !== bodies.length; j++) {
                        var b = bodies[j];
                        if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
                            b.position.vsub(b.previousPosition, interpvelo);
                            interpvelo.scale(h_div_dt, interpvelo);
                            b.position.vadd(interpvelo, b.interpolatedPosition);
                        }
                        else {
                            b.interpolatedPosition.copy(b.position);
                            b.interpolatedQuaternion.copy(b.quaternion);
                        }
                    }
                }
            };
        };
        return CannonJSPlugin;
    }());
    BABYLON.CannonJSPlugin = CannonJSPlugin;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.cannonJSPlugin.js.map

var BABYLON;
(function (BABYLON) {
    /** @hidden */
    var OimoJSPlugin = /** @class */ (function () {
        function OimoJSPlugin(iterations) {
            this.name = "OimoJSPlugin";
            this._tmpImpostorsArray = [];
            this._tmpPositionVector = BABYLON.Vector3.Zero();
            this.BJSOIMO = OIMO;
            this.world = new this.BJSOIMO.World({
                iterations: iterations
            });
            this.world.clear();
        }
        OimoJSPlugin.prototype.setGravity = function (gravity) {
            this.world.gravity.copy(gravity);
        };
        OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
            this.world.timeStep = timeStep;
        };
        OimoJSPlugin.prototype.getTimeStep = function () {
            return this.world.timeStep;
        };
        OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
            var _this = this;
            impostors.forEach(function (impostor) {
                impostor.beforeStep();
            });
            this.world.step();
            impostors.forEach(function (impostor) {
                impostor.afterStep();
                //update the ordered impostors array
                _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
            });
            //check for collisions
            var contact = this.world.contacts;
            while (contact !== null) {
                if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
                    contact = contact.next;
                    continue;
                }
                //is this body colliding with any other? get the impostor
                var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
                var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
                if (!mainImpostor || !collidingImpostor) {
                    contact = contact.next;
                    continue;
                }
                mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
                collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
                contact = contact.next;
            }
        };
        OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
            var mass = impostor.physicsBody.mass;
            impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
        };
        OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
            BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
            this.applyImpulse(impostor, force, contactPoint);
        };
        OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
            var _this = this;
            //parent-child relationship. Does this impostor has a parent impostor?
            if (impostor.parent) {
                if (impostor.physicsBody) {
                    this.removePhysicsBody(impostor);
                    //TODO is that needed?
                    impostor.forceUpdate();
                }
                return;
            }
            if (impostor.isBodyInitRequired()) {
                var bodyConfig = {
                    name: impostor.uniqueId,
                    //Oimo must have mass, also for static objects.
                    config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
                    size: [],
                    type: [],
                    pos: [],
                    posShape: [],
                    rot: [],
                    rotShape: [],
                    move: impostor.getParam("mass") !== 0,
                    density: impostor.getParam("mass"),
                    friction: impostor.getParam("friction"),
                    restitution: impostor.getParam("restitution"),
                    //Supporting older versions of Oimo
                    world: this.world
                };
                var impostors = [impostor];
                var addToArray = function (parent) {
                    if (!parent.getChildMeshes) {
                        return;
                    }
                    parent.getChildMeshes().forEach(function (m) {
                        if (m.physicsImpostor) {
                            impostors.push(m.physicsImpostor);
                            //m.physicsImpostor._init();
                        }
                    });
                };
                addToArray(impostor.object);
                var checkWithEpsilon_1 = function (value) {
                    return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
                };
                var globalQuaternion_1 = new BABYLON.Quaternion();
                impostors.forEach(function (i) {
                    if (!i.object.rotationQuaternion) {
                        return;
                    }
                    //get the correct bounding box
                    var oldQuaternion = i.object.rotationQuaternion;
                    globalQuaternion_1 = oldQuaternion.clone();
                    var rot = oldQuaternion.toEulerAngles();
                    var extendSize = i.getObjectExtendSize();
                    var radToDeg = 57.295779513082320876;
                    if (i === impostor) {
                        var center = impostor.getObjectCenter();
                        impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
                        _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
                        //Can also use Array.prototype.push.apply
                        bodyConfig.pos.push(center.x);
                        bodyConfig.pos.push(center.y);
                        bodyConfig.pos.push(center.z);
                        bodyConfig.posShape.push(0, 0, 0);
                        //tmp solution
                        bodyConfig.rot.push(0);
                        bodyConfig.rot.push(0);
                        bodyConfig.rot.push(0);
                        bodyConfig.rotShape.push(0, 0, 0);
                    }
                    else {
                        var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
                        bodyConfig.posShape.push(localPosition.x);
                        bodyConfig.posShape.push(localPosition.y);
                        bodyConfig.posShape.push(localPosition.z);
                        bodyConfig.pos.push(0, 0, 0);
                        //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
                        bodyConfig.rot.push(0);
                        bodyConfig.rot.push(0);
                        bodyConfig.rot.push(0);
                        bodyConfig.rotShape.push(rot.x * radToDeg);
                        bodyConfig.rotShape.push(rot.y * radToDeg);
                        bodyConfig.rotShape.push(rot.z * radToDeg);
                    }
                    // register mesh
                    switch (i.type) {
                        case BABYLON.PhysicsImpostor.ParticleImpostor:
                            BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
                        case BABYLON.PhysicsImpostor.SphereImpostor:
                            var radiusX = extendSize.x;
                            var radiusY = extendSize.y;
                            var radiusZ = extendSize.z;
                            var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
                            bodyConfig.type.push('sphere');
                            //due to the way oimo works with compounds, add 3 times
                            bodyConfig.size.push(size);
                            bodyConfig.size.push(size);
                            bodyConfig.size.push(size);
                            break;
                        case BABYLON.PhysicsImpostor.CylinderImpostor:
                            var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
                            var sizeY = checkWithEpsilon_1(extendSize.y);
                            bodyConfig.type.push('cylinder');
                            bodyConfig.size.push(sizeX);
                            bodyConfig.size.push(sizeY);
                            //due to the way oimo works with compounds, add one more value.
                            bodyConfig.size.push(sizeY);
                            break;
                        case BABYLON.PhysicsImpostor.PlaneImpostor:
                        case BABYLON.PhysicsImpostor.BoxImpostor:
                        default:
                            var sizeX = checkWithEpsilon_1(extendSize.x);
                            var sizeY = checkWithEpsilon_1(extendSize.y);
                            var sizeZ = checkWithEpsilon_1(extendSize.z);
                            bodyConfig.type.push('box');
                            //if (i === impostor) {
                            bodyConfig.size.push(sizeX);
                            bodyConfig.size.push(sizeY);
                            bodyConfig.size.push(sizeZ);
                            //} else {
                            //    bodyConfig.size.push(0,0,0);
                            //}
                            break;
                    }
                    //actually not needed, but hey...
                    i.object.rotationQuaternion = oldQuaternion;
                });
                impostor.physicsBody = this.world.add(bodyConfig);
                // set the quaternion, ignoring the previously defined (euler) rotation
                impostor.physicsBody.resetQuaternion(globalQuaternion_1);
                // update with delta 0, so the body will reveive the new rotation.
                impostor.physicsBody.updatePosition(0);
            }
            else {
                this._tmpPositionVector.copyFromFloats(0, 0, 0);
            }
            impostor.setDeltaPosition(this._tmpPositionVector);
            //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
            //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
        };
        OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
            //impostor.physicsBody.dispose();
            //Same as : (older oimo versions)
            this.world.removeRigidBody(impostor.physicsBody);
        };
        OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
            var mainBody = impostorJoint.mainImpostor.physicsBody;
            var connectedBody = impostorJoint.connectedImpostor.physicsBody;
            if (!mainBody || !connectedBody) {
                return;
            }
            var jointData = impostorJoint.joint.jointData;
            var options = jointData.nativeParams || {};
            var type;
            var nativeJointData = {
                body1: mainBody,
                body2: connectedBody,
                axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
                axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
                pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
                pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
                min: options.min,
                max: options.max,
                collision: options.collision || jointData.collision,
                spring: options.spring,
                //supporting older version of Oimo
                world: this.world
            };
            switch (impostorJoint.joint.type) {
                case BABYLON.PhysicsJoint.BallAndSocketJoint:
                    type = "jointBall";
                    break;
                case BABYLON.PhysicsJoint.SpringJoint:
                    BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
                    var springData = jointData;
                    nativeJointData.min = springData.length || nativeJointData.min;
                    //Max should also be set, just make sure it is at least min
                    nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
                case BABYLON.PhysicsJoint.DistanceJoint:
                    type = "jointDistance";
                    nativeJointData.max = jointData.maxDistance;
                    break;
                case BABYLON.PhysicsJoint.PrismaticJoint:
                    type = "jointPrisme";
                    break;
                case BABYLON.PhysicsJoint.SliderJoint:
                    type = "jointSlide";
                    break;
                case BABYLON.PhysicsJoint.WheelJoint:
                    type = "jointWheel";
                    break;
                case BABYLON.PhysicsJoint.HingeJoint:
                default:
                    type = "jointHinge";
                    break;
            }
            nativeJointData.type = type;
            impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
        };
        OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
            //Bug in Oimo prevents us from disposing a joint in the playground
            //joint.joint.physicsJoint.dispose();
            //So we will bruteforce it!
            try {
                this.world.removeJoint(impostorJoint.joint.physicsJoint);
            }
            catch (e) {
                BABYLON.Tools.Warn(e);
            }
        };
        OimoJSPlugin.prototype.isSupported = function () {
            return this.BJSOIMO !== undefined;
        };
        OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
            if (!impostor.physicsBody.sleeping) {
                //TODO check that
                /*if (impostor.physicsBody.shapes.next) {
                    var parentShape = this._getLastShape(impostor.physicsBody);
                    impostor.object.position.copyFrom(parentShape.position);
                    console.log(parentShape.position);
                } else {*/
                impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
                //}
                if (impostor.object.rotationQuaternion) {
                    impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
                }
            }
        };
        OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
            var body = impostor.physicsBody;
            body.position.copy(newPosition);
            body.orientation.copy(newRotation);
            body.syncShapes();
            body.awake();
        };
        /*private _getLastShape(body: any): any {
            var lastShape = body.shapes;
            while (lastShape.next) {
                lastShape = lastShape.next;
            }
            return lastShape;
        }*/
        OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
            impostor.physicsBody.linearVelocity.copy(velocity);
        };
        OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
            impostor.physicsBody.angularVelocity.copy(velocity);
        };
        OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
            var v = impostor.physicsBody.linearVelocity;
            if (!v) {
                return null;
            }
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
            var v = impostor.physicsBody.angularVelocity;
            if (!v) {
                return null;
            }
            return new BABYLON.Vector3(v.x, v.y, v.z);
        };
        OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
            var staticBody = mass === 0;
            //this will actually set the body's density and not its mass.
            //But this is how oimo treats the mass variable.
            impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
            impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
        };
        OimoJSPlugin.prototype.getBodyMass = function (impostor) {
            return impostor.physicsBody.shapes.density;
        };
        OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
            return impostor.physicsBody.shapes.friction;
        };
        OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
            impostor.physicsBody.shapes.friction = friction;
        };
        OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
            return impostor.physicsBody.shapes.restitution;
        };
        OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
            impostor.physicsBody.shapes.restitution = restitution;
        };
        OimoJSPlugin.prototype.sleepBody = function (impostor) {
            impostor.physicsBody.sleep();
        };
        OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
            impostor.physicsBody.awake();
        };
        OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
            joint.physicsJoint.limitMotor.upperLimit = maxDistance;
            if (minDistance !== void 0) {
                joint.physicsJoint.limitMotor.lowerLimit = minDistance;
            }
        };
        OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
            //TODO separate rotational and transational motors.
            var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
            if (motor) {
                motor.setMotor(speed, maxForce);
            }
        };
        OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
            //TODO separate rotational and transational motors.
            var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
            if (motor) {
                motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
            }
        };
        OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
            var body = impostor.physicsBody;
            mesh.position.x = body.position.x;
            mesh.position.y = body.position.y;
            mesh.position.z = body.position.z;
            if (mesh.rotationQuaternion) {
                mesh.rotationQuaternion.x = body.orientation.x;
                mesh.rotationQuaternion.y = body.orientation.y;
                mesh.rotationQuaternion.z = body.orientation.z;
                mesh.rotationQuaternion.w = body.orientation.s;
            }
        };
        OimoJSPlugin.prototype.getRadius = function (impostor) {
            return impostor.physicsBody.shapes.radius;
        };
        OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
            var shape = impostor.physicsBody.shapes;
            result.x = shape.halfWidth * 2;
            result.y = shape.halfHeight * 2;
            result.z = shape.halfDepth * 2;
        };
        OimoJSPlugin.prototype.dispose = function () {
            this.world.clear();
        };
        return OimoJSPlugin;
    }());
    BABYLON.OimoJSPlugin = OimoJSPlugin;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.oimoJSPlugin.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Gets the current physics engine
     * @returns a IPhysicsEngine or null if none attached
     */
    BABYLON.Scene.prototype.getPhysicsEngine = function () {
        return this._physicsEngine;
    };
    /**
     * Enables physics to the current scene
     * @param gravity defines the scene's gravity for the physics engine
     * @param plugin defines the physics engine to be used. defaults to OimoJS.
     * @return a boolean indicating if the physics engine was initialized
     */
    BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
        if (gravity === void 0) { gravity = null; }
        if (this._physicsEngine) {
            return true;
        }
        // Register the component to the scene
        var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
        if (!component) {
            component = new PhysicsEngineSceneComponent(this);
            this._addComponent(component);
        }
        try {
            this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
            return true;
        }
        catch (e) {
            BABYLON.Tools.Error(e.message);
            return false;
        }
    };
    /**
     * Disables and disposes the physics engine associated with the scene
     */
    BABYLON.Scene.prototype.disablePhysicsEngine = function () {
        if (!this._physicsEngine) {
            return;
        }
        this._physicsEngine.dispose();
        this._physicsEngine = null;
    };
    /**
     * Gets a boolean indicating if there is an active physics engine
     * @returns a boolean indicating if there is an active physics engine
     */
    BABYLON.Scene.prototype.isPhysicsEnabled = function () {
        return this._physicsEngine !== undefined;
    };
    /**
     * Deletes a physics compound impostor
     * @param compound defines the compound to delete
     */
    BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
        var mesh = compound.parts[0].mesh;
        if (mesh.physicsImpostor) {
            mesh.physicsImpostor.dispose( /*true*/);
            mesh.physicsImpostor = null;
        }
    };
    /** @hidden */
    BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
        if (this._physicsEngine) {
            this.onBeforePhysicsObservable.notifyObservers(this);
            this._physicsEngine._step(step / 1000);
            this.onAfterPhysicsObservable.notifyObservers(this);
        }
    };
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
        get: function () {
            return this._physicsImpostor;
        },
        set: function (value) {
            var _this = this;
            if (this._physicsImpostor === value) {
                return;
            }
            if (this._disposePhysicsObserver) {
                this.onDisposeObservable.remove(this._disposePhysicsObserver);
            }
            this._physicsImpostor = value;
            if (value) {
                this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
                    // Physics
                    if (_this.physicsImpostor) {
                        _this.physicsImpostor.dispose( /*!doNotRecurse*/);
                        _this.physicsImpostor = null;
                    }
                });
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Gets the current physics impostor
     * @see http://doc.babylonjs.com/features/physics_engine
     * @returns a physics impostor or null
     */
    BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
        return this.physicsImpostor;
    };
    /**
     * Apply a physic impulse to the mesh
     * @param force defines the force to apply
     * @param contactPoint defines where to apply the force
     * @returns the current mesh
     * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
     */
    BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
        if (!this.physicsImpostor) {
            return this;
        }
        this.physicsImpostor.applyImpulse(force, contactPoint);
        return this;
    };
    /**
     * Creates a physic joint between two meshes
     * @param otherMesh defines the other mesh to use
     * @param pivot1 defines the pivot to use on this mesh
     * @param pivot2 defines the pivot to use on the other mesh
     * @param options defines additional options (can be plugin dependent)
     * @returns the current mesh
     * @see https://www.babylonjs-playground.com/#0BS5U0#0
     */
    BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
        if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
            return this;
        }
        this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
            mainPivot: pivot1,
            connectedPivot: pivot2,
            nativeParams: options
        });
        return this;
    };
    /**
     * Defines the physics engine scene component responsible to manage a physics engine
     */
    var PhysicsEngineSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function PhysicsEngineSceneComponent(scene) {
            var _this = this;
            /**
             * The component name helpful to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
            this.scene = scene;
            this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
            this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
            // Replace the function used to get the deterministic frame time
            this.scene.getDeterministicFrameTime = function () {
                if (_this.scene._physicsEngine) {
                    return _this.scene._physicsEngine.getTimeStep() * 1000;
                }
                return 1000.0 / 60.0;
            };
        }
        /**
         * Registers the component in a given scene
         */
        PhysicsEngineSceneComponent.prototype.register = function () {
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        PhysicsEngineSceneComponent.prototype.rebuild = function () {
            // Nothing to do for this component
        };
        /**
         * Disposes the component and the associated ressources
         */
        PhysicsEngineSceneComponent.prototype.dispose = function () {
            this.scene.onBeforePhysicsObservable.clear();
            this.scene.onAfterPhysicsObservable.clear();
            if (this.scene._physicsEngine) {
                this.scene.disablePhysicsEngine();
            }
        };
        return PhysicsEngineSceneComponent;
    }());
    BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.physicsEngineComponent.js.map

var BABYLON;
(function (BABYLON) {
    // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
    // All values and structures referenced from:
    // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
    var DDS_MAGIC = 0x20534444;
    var 
    //DDSD_CAPS = 0x1,
    //DDSD_HEIGHT = 0x2,
    //DDSD_WIDTH = 0x4,
    //DDSD_PITCH = 0x8,
    //DDSD_PIXELFORMAT = 0x1000,
    DDSD_MIPMAPCOUNT = 0x20000;
    //DDSD_LINEARSIZE = 0x80000,
    //DDSD_DEPTH = 0x800000;
    // var DDSCAPS_COMPLEX = 0x8,
    //     DDSCAPS_MIPMAP = 0x400000,
    //     DDSCAPS_TEXTURE = 0x1000;
    var DDSCAPS2_CUBEMAP = 0x200;
    // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
    // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
    // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
    // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
    // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
    // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
    // DDSCAPS2_VOLUME = 0x200000;
    var 
    //DDPF_ALPHAPIXELS = 0x1,
    //DDPF_ALPHA = 0x2,
    DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, 
    //DDPF_YUV = 0x200,
    DDPF_LUMINANCE = 0x20000;
    function FourCCToInt32(value) {
        return value.charCodeAt(0) +
            (value.charCodeAt(1) << 8) +
            (value.charCodeAt(2) << 16) +
            (value.charCodeAt(3) << 24);
    }
    function Int32ToFourCC(value) {
        return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
    }
    var FOURCC_DXT1 = FourCCToInt32("DXT1");
    var FOURCC_DXT3 = FourCCToInt32("DXT3");
    var FOURCC_DXT5 = FourCCToInt32("DXT5");
    var FOURCC_DX10 = FourCCToInt32("DX10");
    var FOURCC_D3DFMT_R16G16B16A16F = 113;
    var FOURCC_D3DFMT_R32G32B32A32F = 116;
    var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
    var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
    var headerLengthInt = 31; // The header length in 32 bit ints
    // Offsets into the header array
    var off_magic = 0;
    var off_size = 1;
    var off_flags = 2;
    var off_height = 3;
    var off_width = 4;
    var off_mipmapCount = 7;
    var off_pfFlags = 20;
    var off_pfFourCC = 21;
    var off_RGBbpp = 22;
    var off_RMask = 23;
    var off_GMask = 24;
    var off_BMask = 25;
    var off_AMask = 26;
    // var off_caps1 = 27;
    var off_caps2 = 28;
    // var off_caps3 = 29;
    // var off_caps4 = 30;
    var off_dxgiFormat = 32;
    /**
     * Class used to provide DDS decompression tools
     */
    var DDSTools = /** @class */ (function () {
        function DDSTools() {
        }
        /**
         * Gets DDS information from an array buffer
         * @param arrayBuffer defines the array buffer to read data from
         * @returns the DDS information
         */
        DDSTools.GetDDSInfo = function (arrayBuffer) {
            var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
            var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
            var mipmapCount = 1;
            if (header[off_flags] & DDSD_MIPMAPCOUNT) {
                mipmapCount = Math.max(1, header[off_mipmapCount]);
            }
            var fourCC = header[off_pfFourCC];
            var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
            var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            switch (fourCC) {
                case FOURCC_D3DFMT_R16G16B16A16F:
                    textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                    break;
                case FOURCC_D3DFMT_R32G32B32A32F:
                    textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
                    break;
                case FOURCC_DX10:
                    if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
                        textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                        break;
                    }
            }
            return {
                width: header[off_width],
                height: header[off_height],
                mipmapCount: mipmapCount,
                isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
                isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
                isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
                isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
                isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
                dxgiFormat: dxgiFormat,
                textureType: textureType
            };
        };
        DDSTools._ToHalfFloat = function (value) {
            if (!DDSTools._FloatView) {
                DDSTools._FloatView = new Float32Array(1);
                DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
            }
            DDSTools._FloatView[0] = value;
            var x = DDSTools._Int32View[0];
            var bits = (x >> 16) & 0x8000; /* Get the sign */
            var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
            var e = (x >> 23) & 0xff; /* Using int is faster here */
            /* If zero, or denormal, or exponent underflows too much for a denormal
            * half, return signed zero. */
            if (e < 103) {
                return bits;
            }
            /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
            if (e > 142) {
                bits |= 0x7c00;
                /* If exponent was 0xff and one mantissa bit was set, it means NaN,
                * not Inf, so make sure we set one mantissa bit too. */
                bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
                return bits;
            }
            /* If exponent underflows but not too much, return a denormal */
            if (e < 113) {
                m |= 0x0800;
                /* Extra rounding may overflow and set mantissa to 0 and exponent
                * to 1, which is OK. */
                bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
                return bits;
            }
            bits |= ((e - 112) << 10) | (m >> 1);
            bits += m & 1;
            return bits;
        };
        DDSTools._FromHalfFloat = function (value) {
            var s = (value & 0x8000) >> 15;
            var e = (value & 0x7C00) >> 10;
            var f = value & 0x03FF;
            if (e === 0) {
                return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
            }
            else if (e == 0x1F) {
                return f ? NaN : ((s ? -1 : 1) * Infinity);
            }
            return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
        };
        DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
            var destArray = new Float32Array(dataLength);
            var srcData = new Uint16Array(arrayBuffer, dataOffset);
            var index = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var srcPos = (x + y * width) * 4;
                    destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
                    destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
                    destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
                    if (DDSTools.StoreLODInAlphaChannel) {
                        destArray[index + 3] = lod;
                    }
                    else {
                        destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
                    }
                    index += 4;
                }
            }
            return destArray;
        };
        DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
            if (DDSTools.StoreLODInAlphaChannel) {
                var destArray = new Uint16Array(dataLength);
                var srcData = new Uint16Array(arrayBuffer, dataOffset);
                var index = 0;
                for (var y = 0; y < height; y++) {
                    for (var x = 0; x < width; x++) {
                        var srcPos = (x + y * width) * 4;
                        destArray[index] = srcData[srcPos];
                        destArray[index + 1] = srcData[srcPos + 1];
                        destArray[index + 2] = srcData[srcPos + 2];
                        destArray[index + 3] = DDSTools._ToHalfFloat(lod);
                        index += 4;
                    }
                }
                return destArray;
            }
            return new Uint16Array(arrayBuffer, dataOffset, dataLength);
        };
        DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
            if (DDSTools.StoreLODInAlphaChannel) {
                var destArray = new Float32Array(dataLength);
                var srcData = new Float32Array(arrayBuffer, dataOffset);
                var index = 0;
                for (var y = 0; y < height; y++) {
                    for (var x = 0; x < width; x++) {
                        var srcPos = (x + y * width) * 4;
                        destArray[index] = srcData[srcPos];
                        destArray[index + 1] = srcData[srcPos + 1];
                        destArray[index + 2] = srcData[srcPos + 2];
                        destArray[index + 3] = lod;
                        index += 4;
                    }
                }
                return destArray;
            }
            return new Float32Array(arrayBuffer, dataOffset, dataLength);
        };
        DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
            var destArray = new Uint8Array(dataLength);
            var srcData = new Float32Array(arrayBuffer, dataOffset);
            var index = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var srcPos = (x + y * width) * 4;
                    destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
                    destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
                    destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
                    if (DDSTools.StoreLODInAlphaChannel) {
                        destArray[index + 3] = lod;
                    }
                    else {
                        destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
                    }
                    index += 4;
                }
            }
            return destArray;
        };
        DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
            var destArray = new Uint8Array(dataLength);
            var srcData = new Uint16Array(arrayBuffer, dataOffset);
            var index = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var srcPos = (x + y * width) * 4;
                    destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
                    destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
                    destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
                    if (DDSTools.StoreLODInAlphaChannel) {
                        destArray[index + 3] = lod;
                    }
                    else {
                        destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
                    }
                    index += 4;
                }
            }
            return destArray;
        };
        DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
            var byteArray = new Uint8Array(dataLength);
            var srcData = new Uint8Array(arrayBuffer, dataOffset);
            var index = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var srcPos = (x + y * width) * 4;
                    byteArray[index] = srcData[srcPos + rOffset];
                    byteArray[index + 1] = srcData[srcPos + gOffset];
                    byteArray[index + 2] = srcData[srcPos + bOffset];
                    byteArray[index + 3] = srcData[srcPos + aOffset];
                    index += 4;
                }
            }
            return byteArray;
        };
        DDSTools._ExtractLongWordOrder = function (value) {
            if (value === 0 || value === 255 || value === -16777216) {
                return 0;
            }
            return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
        };
        DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
            var byteArray = new Uint8Array(dataLength);
            var srcData = new Uint8Array(arrayBuffer, dataOffset);
            var index = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var srcPos = (x + y * width) * 3;
                    byteArray[index] = srcData[srcPos + rOffset];
                    byteArray[index + 1] = srcData[srcPos + gOffset];
                    byteArray[index + 2] = srcData[srcPos + bOffset];
                    index += 3;
                }
            }
            return byteArray;
        };
        DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
            var byteArray = new Uint8Array(dataLength);
            var srcData = new Uint8Array(arrayBuffer, dataOffset);
            var index = 0;
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var srcPos = (x + y * width);
                    byteArray[index] = srcData[srcPos];
                    index++;
                }
            }
            return byteArray;
        };
        /**
         * Uploads DDS Levels to a Babylon Texture
         * @hidden
         */
        DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
            if (lodIndex === void 0) { lodIndex = -1; }
            var sphericalPolynomialFaces = null;
            if (info.sphericalPolynomial) {
                sphericalPolynomialFaces = new Array();
            }
            var ext = engine.getCaps().s3tc;
            var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
            var fourCC, width, height, dataLength = 0, dataOffset;
            var byteArray, mipmapCount, mip;
            var internalCompressedFormat = 0;
            var blockBytes = 1;
            if (header[off_magic] !== DDS_MAGIC) {
                BABYLON.Tools.Error("Invalid magic number in DDS header");
                return;
            }
            if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
                BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
                return;
            }
            if (info.isCompressed && !ext) {
                BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
                return;
            }
            var bpp = header[off_RGBbpp];
            dataOffset = header[off_size] + 4;
            var computeFormats = false;
            if (info.isFourCC) {
                fourCC = header[off_pfFourCC];
                switch (fourCC) {
                    case FOURCC_DXT1:
                        blockBytes = 8;
                        internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
                        break;
                    case FOURCC_DXT3:
                        blockBytes = 16;
                        internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
                        break;
                    case FOURCC_DXT5:
                        blockBytes = 16;
                        internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
                        break;
                    case FOURCC_D3DFMT_R16G16B16A16F:
                        computeFormats = true;
                        break;
                    case FOURCC_D3DFMT_R32G32B32A32F:
                        computeFormats = true;
                        break;
                    case FOURCC_DX10:
                        // There is an additionnal header so dataOffset need to be changed
                        dataOffset += 5 * 4; // 5 uints
                        var supported = false;
                        switch (info.dxgiFormat) {
                            case DXGI_FORMAT_R16G16B16A16_FLOAT:
                                computeFormats = true;
                                supported = true;
                                break;
                            case DXGI_FORMAT_B8G8R8X8_UNORM:
                                info.isRGB = true;
                                info.isFourCC = false;
                                bpp = 32;
                                supported = true;
                                break;
                        }
                        if (supported) {
                            break;
                        }
                    default:
                        console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
                        return;
                }
            }
            var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
            var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
            var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
            var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
            if (computeFormats) {
                internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
            }
            mipmapCount = 1;
            if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
                mipmapCount = Math.max(1, header[off_mipmapCount]);
            }
            for (var face = 0; face < faces; face++) {
                width = header[off_width];
                height = header[off_height];
                for (mip = 0; mip < mipmapCount; ++mip) {
                    if (lodIndex === -1 || lodIndex === mip) {
                        // In case of fixed LOD, if the lod has just been uploaded, early exit.
                        var i = (lodIndex === -1) ? mip : 0;
                        if (!info.isCompressed && info.isFourCC) {
                            texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
                            dataLength = width * height * 4;
                            var floatArray = null;
                            if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
                                if (bpp === 128) {
                                    floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
                                    if (sphericalPolynomialFaces && i == 0) {
                                        sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
                                    }
                                }
                                else if (bpp === 64) {
                                    floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
                                    if (sphericalPolynomialFaces && i == 0) {
                                        sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
                                    }
                                }
                                texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                            }
                            else {
                                if (bpp === 128) {
                                    texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
                                    floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
                                    if (sphericalPolynomialFaces && i == 0) {
                                        sphericalPolynomialFaces.push(floatArray);
                                    }
                                }
                                else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
                                    texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
                                    floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
                                    if (sphericalPolynomialFaces && i == 0) {
                                        sphericalPolynomialFaces.push(floatArray);
                                    }
                                }
                                else { // 64
                                    texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                                    floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
                                    if (sphericalPolynomialFaces && i == 0) {
                                        sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
                                    }
                                }
                            }
                            if (floatArray) {
                                engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
                            }
                        }
                        else if (info.isRGB) {
                            texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                            if (bpp === 24) {
                                texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
                                dataLength = width * height * 3;
                                byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
                                engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
                            }
                            else { // 32
                                texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
                                dataLength = width * height * 4;
                                byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
                                engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
                            }
                        }
                        else if (info.isLuminance) {
                            var unpackAlignment = engine._getUnpackAlignement();
                            var unpaddedRowSize = width;
                            var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
                            dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
                            byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
                            texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
                            texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                            engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
                        }
                        else {
                            dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
                            byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
                            texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                            engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
                        }
                    }
                    dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
                    width *= 0.5;
                    height *= 0.5;
                    width = Math.max(1.0, width);
                    height = Math.max(1.0, height);
                }
                if (currentFace !== undefined) {
                    // Loading a single face
                    break;
                }
            }
            if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
                info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
                    size: header[off_width],
                    right: sphericalPolynomialFaces[0],
                    left: sphericalPolynomialFaces[1],
                    up: sphericalPolynomialFaces[2],
                    down: sphericalPolynomialFaces[3],
                    front: sphericalPolynomialFaces[4],
                    back: sphericalPolynomialFaces[5],
                    format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
                    type: BABYLON.Engine.TEXTURETYPE_FLOAT,
                    gammaSpace: false,
                });
            }
            else {
                info.sphericalPolynomial = undefined;
            }
        };
        /**
         * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
         */
        DDSTools.StoreLODInAlphaChannel = false;
        return DDSTools;
    }());
    BABYLON.DDSTools = DDSTools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.dds.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Implementation of the DDS Texture Loader.
     */
    var DDSTextureLoader = /** @class */ (function () {
        function DDSTextureLoader() {
            /**
             * Defines wether the loader supports cascade loading the different faces.
             */
            this.supportCascades = true;
        }
        /**
         * This returns if the loader support the current file information.
         * @param extension defines the file extension of the file being loaded
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @param fallback defines the fallback internal texture if any
         * @param isBase64 defines whether the texture is encoded as a base64
         * @param isBuffer defines whether the texture data are stored as a buffer
         * @returns true if the loader can load the specified file
         */
        DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
            return extension.indexOf(".dds") === 0;
        };
        /**
         * Transform the url before loading if required.
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the transformed texture
         */
        DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
            return rootUrl;
        };
        /**
         * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the fallback texture
         */
        DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
            return null;
        };
        /**
         * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param createPolynomials will be true if polynomials have been requested
         * @param onLoad defines the callback to trigger once the texture is ready
         * @param onError defines the callback to trigger in case of error
         */
        DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
            var engine = texture.getEngine();
            var info;
            var loadMipmap = false;
            if (Array.isArray(imgs)) {
                for (var index = 0; index < imgs.length; index++) {
                    var data_1 = imgs[index];
                    info = BABYLON.DDSTools.GetDDSInfo(data_1);
                    texture.width = info.width;
                    texture.height = info.height;
                    loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
                    engine._unpackFlipY(info.isCompressed);
                    BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
                    if (!info.isFourCC && info.mipmapCount === 1) {
                        engine.generateMipMapsForCubemap(texture);
                    }
                }
            }
            else {
                var data = imgs;
                info = BABYLON.DDSTools.GetDDSInfo(data);
                texture.width = info.width;
                texture.height = info.height;
                if (createPolynomials) {
                    info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
                }
                loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
                engine._unpackFlipY(info.isCompressed);
                BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
                if (!info.isFourCC && info.mipmapCount === 1) {
                    engine.generateMipMapsForCubemap(texture);
                }
            }
            engine._setCubeMapTextureParams(loadMipmap);
            texture.isReady = true;
            if (onLoad) {
                onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
            }
        };
        /**
         * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param callback defines the method to call once ready to upload
         */
        DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
            var info = BABYLON.DDSTools.GetDDSInfo(data);
            var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
            callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
                BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
            });
        };
        return DDSTextureLoader;
    }());
    // Register the loader.
    BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.ddsTextureLoader.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Based on jsTGALoader - Javascript loader for TGA file
     * By Vincent Thibault
     * @see http://blog.robrowser.com/javascript-tga-loader.html
     */
    var TGATools = /** @class */ (function () {
        function TGATools() {
        }
        /**
         * Gets the header of a TGA file
         * @param data defines the TGA data
         * @returns the header
         */
        TGATools.GetTGAHeader = function (data) {
            var offset = 0;
            var header = {
                id_length: data[offset++],
                colormap_type: data[offset++],
                image_type: data[offset++],
                colormap_index: data[offset++] | data[offset++] << 8,
                colormap_length: data[offset++] | data[offset++] << 8,
                colormap_size: data[offset++],
                origin: [
                    data[offset++] | data[offset++] << 8,
                    data[offset++] | data[offset++] << 8
                ],
                width: data[offset++] | data[offset++] << 8,
                height: data[offset++] | data[offset++] << 8,
                pixel_size: data[offset++],
                flags: data[offset++]
            };
            return header;
        };
        /**
         * Uploads TGA content to a Babylon Texture
         * @hidden
         */
        TGATools.UploadContent = function (texture, data) {
            // Not enough data to contain header ?
            if (data.length < 19) {
                BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
                return;
            }
            // Read Header
            var offset = 18;
            var header = TGATools.GetTGAHeader(data);
            // Assume it's a valid Targa file.
            if (header.id_length + offset > data.length) {
                BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
                return;
            }
            // Skip not needed data
            offset += header.id_length;
            var use_rle = false;
            var use_pal = false;
            var use_grey = false;
            // Get some informations.
            switch (header.image_type) {
                case TGATools._TYPE_RLE_INDEXED:
                    use_rle = true;
                case TGATools._TYPE_INDEXED:
                    use_pal = true;
                    break;
                case TGATools._TYPE_RLE_RGB:
                    use_rle = true;
                case TGATools._TYPE_RGB:
                    // use_rgb = true;
                    break;
                case TGATools._TYPE_RLE_GREY:
                    use_rle = true;
                case TGATools._TYPE_GREY:
                    use_grey = true;
                    break;
            }
            var pixel_data;
            // var numAlphaBits = header.flags & 0xf;
            var pixel_size = header.pixel_size >> 3;
            var pixel_total = header.width * header.height * pixel_size;
            // Read palettes
            var palettes;
            if (use_pal) {
                palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
            }
            // Read LRE
            if (use_rle) {
                pixel_data = new Uint8Array(pixel_total);
                var c, count, i;
                var localOffset = 0;
                var pixels = new Uint8Array(pixel_size);
                while (offset < pixel_total && localOffset < pixel_total) {
                    c = data[offset++];
                    count = (c & 0x7f) + 1;
                    // RLE pixels
                    if (c & 0x80) {
                        // Bind pixel tmp array
                        for (i = 0; i < pixel_size; ++i) {
                            pixels[i] = data[offset++];
                        }
                        // Copy pixel array
                        for (i = 0; i < count; ++i) {
                            pixel_data.set(pixels, localOffset + i * pixel_size);
                        }
                        localOffset += pixel_size * count;
                    }
                    // Raw pixels
                    else {
                        count *= pixel_size;
                        for (i = 0; i < count; ++i) {
                            pixel_data[localOffset + i] = data[offset++];
                        }
                        localOffset += count;
                    }
                }
            }
            // RAW Pixels
            else {
                pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
            }
            // Load to texture
            var x_start, y_start, x_step, y_step, y_end, x_end;
            switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
                default:
                case TGATools._ORIGIN_UL:
                    x_start = 0;
                    x_step = 1;
                    x_end = header.width;
                    y_start = 0;
                    y_step = 1;
                    y_end = header.height;
                    break;
                case TGATools._ORIGIN_BL:
                    x_start = 0;
                    x_step = 1;
                    x_end = header.width;
                    y_start = header.height - 1;
                    y_step = -1;
                    y_end = -1;
                    break;
                case TGATools._ORIGIN_UR:
                    x_start = header.width - 1;
                    x_step = -1;
                    x_end = -1;
                    y_start = 0;
                    y_step = 1;
                    y_end = header.height;
                    break;
                case TGATools._ORIGIN_BR:
                    x_start = header.width - 1;
                    x_step = -1;
                    x_end = -1;
                    y_start = header.height - 1;
                    y_step = -1;
                    y_end = -1;
                    break;
            }
            // Load the specify method
            var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
            var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
            var engine = texture.getEngine();
            engine._uploadDataToTextureDirectly(texture, imageData);
        };
        /** @hidden */
        TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
            var image = pixel_data, colormap = palettes;
            var width = header.width, height = header.height;
            var color, i = 0, x, y;
            var imageData = new Uint8Array(width * height * 4);
            for (y = y_start; y !== y_end; y += y_step) {
                for (x = x_start; x !== x_end; x += x_step, i++) {
                    color = image[i];
                    imageData[(x + width * y) * 4 + 3] = 255;
                    imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
                    imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
                    imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
                }
            }
            return imageData;
        };
        /** @hidden */
        TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
            var image = pixel_data;
            var width = header.width, height = header.height;
            var color, i = 0, x, y;
            var imageData = new Uint8Array(width * height * 4);
            for (y = y_start; y !== y_end; y += y_step) {
                for (x = x_start; x !== x_end; x += x_step, i += 2) {
                    color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
                    var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
                    var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
                    var b = ((color & 0x001F) * 255) / 0x1F | 0;
                    imageData[(x + width * y) * 4 + 0] = r;
                    imageData[(x + width * y) * 4 + 1] = g;
                    imageData[(x + width * y) * 4 + 2] = b;
                    imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
                }
            }
            return imageData;
        };
        /** @hidden */
        TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
            var image = pixel_data;
            var width = header.width, height = header.height;
            var i = 0, x, y;
            var imageData = new Uint8Array(width * height * 4);
            for (y = y_start; y !== y_end; y += y_step) {
                for (x = x_start; x !== x_end; x += x_step, i += 3) {
                    imageData[(x + width * y) * 4 + 3] = 255;
                    imageData[(x + width * y) * 4 + 2] = image[i + 0];
                    imageData[(x + width * y) * 4 + 1] = image[i + 1];
                    imageData[(x + width * y) * 4 + 0] = image[i + 2];
                }
            }
            return imageData;
        };
        /** @hidden */
        TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
            var image = pixel_data;
            var width = header.width, height = header.height;
            var i = 0, x, y;
            var imageData = new Uint8Array(width * height * 4);
            for (y = y_start; y !== y_end; y += y_step) {
                for (x = x_start; x !== x_end; x += x_step, i += 4) {
                    imageData[(x + width * y) * 4 + 2] = image[i + 0];
                    imageData[(x + width * y) * 4 + 1] = image[i + 1];
                    imageData[(x + width * y) * 4 + 0] = image[i + 2];
                    imageData[(x + width * y) * 4 + 3] = image[i + 3];
                }
            }
            return imageData;
        };
        /** @hidden */
        TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
            var image = pixel_data;
            var width = header.width, height = header.height;
            var color, i = 0, x, y;
            var imageData = new Uint8Array(width * height * 4);
            for (y = y_start; y !== y_end; y += y_step) {
                for (x = x_start; x !== x_end; x += x_step, i++) {
                    color = image[i];
                    imageData[(x + width * y) * 4 + 0] = color;
                    imageData[(x + width * y) * 4 + 1] = color;
                    imageData[(x + width * y) * 4 + 2] = color;
                    imageData[(x + width * y) * 4 + 3] = 255;
                }
            }
            return imageData;
        };
        /** @hidden */
        TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
            var image = pixel_data;
            var width = header.width, height = header.height;
            var i = 0, x, y;
            var imageData = new Uint8Array(width * height * 4);
            for (y = y_start; y !== y_end; y += y_step) {
                for (x = x_start; x !== x_end; x += x_step, i += 2) {
                    imageData[(x + width * y) * 4 + 0] = image[i + 0];
                    imageData[(x + width * y) * 4 + 1] = image[i + 0];
                    imageData[(x + width * y) * 4 + 2] = image[i + 0];
                    imageData[(x + width * y) * 4 + 3] = image[i + 1];
                }
            }
            return imageData;
        };
        //private static _TYPE_NO_DATA = 0;
        TGATools._TYPE_INDEXED = 1;
        TGATools._TYPE_RGB = 2;
        TGATools._TYPE_GREY = 3;
        TGATools._TYPE_RLE_INDEXED = 9;
        TGATools._TYPE_RLE_RGB = 10;
        TGATools._TYPE_RLE_GREY = 11;
        TGATools._ORIGIN_MASK = 0x30;
        TGATools._ORIGIN_SHIFT = 0x04;
        TGATools._ORIGIN_BL = 0x00;
        TGATools._ORIGIN_BR = 0x01;
        TGATools._ORIGIN_UL = 0x02;
        TGATools._ORIGIN_UR = 0x03;
        return TGATools;
    }());
    BABYLON.TGATools = TGATools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.tga.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Implementation of the TGA Texture Loader.
     */
    var TGATextureLoader = /** @class */ (function () {
        function TGATextureLoader() {
            /**
             * Defines wether the loader supports cascade loading the different faces.
             */
            this.supportCascades = false;
        }
        /**
         * This returns if the loader support the current file information.
         * @param extension defines the file extension of the file being loaded
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @param fallback defines the fallback internal texture if any
         * @param isBase64 defines whether the texture is encoded as a base64
         * @param isBuffer defines whether the texture data are stored as a buffer
         * @returns true if the loader can load the specified file
         */
        TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
            return extension.indexOf(".tga") === 0;
        };
        /**
         * Transform the url before loading if required.
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the transformed texture
         */
        TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
            return rootUrl;
        };
        /**
         * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the fallback texture
         */
        TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
            return null;
        };
        /**
         * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param createPolynomials will be true if polynomials have been requested
         * @param onLoad defines the callback to trigger once the texture is ready
         * @param onError defines the callback to trigger in case of error
         */
        TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
            throw ".env not supported in Cube.";
        };
        /**
         * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param callback defines the method to call once ready to upload
         */
        TGATextureLoader.prototype.loadData = function (data, texture, callback) {
            var uintData = new Uint8Array(data);
            var header = BABYLON.TGATools.GetTGAHeader(uintData);
            callback(header.width, header.height, texture.generateMipMaps, false, function () {
                BABYLON.TGATools.UploadContent(texture, uintData);
            });
        };
        return TGATextureLoader;
    }());
    // Register the loader.
    BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.tgaTextureLoader.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
     * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
     */
    var KhronosTextureContainer = /** @class */ (function () {
        /**
         * Creates a new KhronosTextureContainer
         * @param arrayBuffer contents of the KTX container file
         * @param facesExpected should be either 1 or 6, based whether a cube texture or or
         * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
         * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
         */
        function KhronosTextureContainer(
        /** contents of the KTX container file */
        arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
            this.arrayBuffer = arrayBuffer;
            // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
            // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
            // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
            var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
            if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
                identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
                BABYLON.Tools.Error("texture missing KTX identifier");
                return;
            }
            // load the reset of the header in native 32 bit int
            var header = new Int32Array(this.arrayBuffer, 12, 13);
            // determine of the remaining header values are recorded in the opposite endianness & require conversion
            var oppositeEndianess = header[0] === 0x01020304;
            // read all the header elements in order they exist in the file, without modification (sans endainness)
            this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
            this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
            this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
            this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
            this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
            this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
            this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
            this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
            this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
            this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
            this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
            this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
            // Make sure we have a compressed type.  Not only reduces work, but probably better to let dev know they are not compressing.
            if (this.glType !== 0) {
                BABYLON.Tools.Error("only compressed formats currently supported");
                return;
            }
            else {
                // value of zero is an indication to generate mipmaps @ runtime.  Not usually allowed for compressed, so disregard.
                this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
            }
            if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
                BABYLON.Tools.Error("only 2D textures currently supported");
                return;
            }
            if (this.numberOfArrayElements !== 0) {
                BABYLON.Tools.Error("texture arrays not currently supported");
                return;
            }
            if (this.numberOfFaces !== facesExpected) {
                BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
                return;
            }
            // we now have a completely validated file, so could use existence of loadType as success
            // would need to make this more elaborate & adjust checks above to support more than one load type
            this.loadType = KhronosTextureContainer.COMPRESSED_2D;
        }
        //
        /**
         * Revert the endianness of a value.
         * Not as fast hardware based, but will probably never need to use
         * @param val defines the value to convert
         * @returns the new value
         */
        KhronosTextureContainer.prototype.switchEndianness = function (val) {
            return ((val & 0xFF) << 24)
                | ((val & 0xFF00) << 8)
                | ((val >> 8) & 0xFF00)
                | ((val >> 24) & 0xFF);
        };
        /**
         * Uploads KTX content to a Babylon Texture.
         * It is assumed that the texture has already been created & is currently bound
         * @hidden
         */
        KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
            switch (this.loadType) {
                case KhronosTextureContainer.COMPRESSED_2D:
                    this._upload2DCompressedLevels(texture, loadMipmaps);
                    break;
                case KhronosTextureContainer.TEX_2D:
                case KhronosTextureContainer.COMPRESSED_3D:
                case KhronosTextureContainer.TEX_3D:
            }
        };
        KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
            // initialize width & height for level 1
            var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
            var width = this.pixelWidth;
            var height = this.pixelHeight;
            var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
            for (var level = 0; level < mipmapCount; level++) {
                var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
                dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
                for (var face = 0; face < this.numberOfFaces; face++) {
                    var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
                    var engine = texture.getEngine();
                    engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
                    dataOffset += imageSize; // add size of the image for the next face/mipmap
                    dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
                }
                width = Math.max(1.0, width * 0.5);
                height = Math.max(1.0, height * 0.5);
            }
        };
        KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
        // load types
        KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
        KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
        KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
        KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
        return KhronosTextureContainer;
    }());
    BABYLON.KhronosTextureContainer = KhronosTextureContainer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.khronosTextureContainer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Implementation of the KTX Texture Loader.
     */
    var KTXTextureLoader = /** @class */ (function () {
        function KTXTextureLoader() {
            /**
             * Defines wether the loader supports cascade loading the different faces.
             */
            this.supportCascades = false;
        }
        /**
         * This returns if the loader support the current file information.
         * @param extension defines the file extension of the file being loaded
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @param fallback defines the fallback internal texture if any
         * @param isBase64 defines whether the texture is encoded as a base64
         * @param isBuffer defines whether the texture data are stored as a buffer
         * @returns true if the loader can load the specified file
         */
        KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
            if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
                return true;
            }
            return false;
        };
        /**
         * Transform the url before loading if required.
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the transformed texture
         */
        KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
            var lastDot = rootUrl.lastIndexOf('.');
            return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
        };
        /**
         * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the fallback texture
         */
        KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
            // remove the format appended to the rootUrl in the original createCubeTexture call.
            var exp = new RegExp("" + textureFormatInUse + "$");
            return rootUrl.replace(exp, "");
        };
        /**
         * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param createPolynomials will be true if polynomials have been requested
         * @param onLoad defines the callback to trigger once the texture is ready
         * @param onError defines the callback to trigger in case of error
         */
        KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
            if (Array.isArray(data)) {
                return;
            }
            var engine = texture.getEngine();
            var ktx = new BABYLON.KhronosTextureContainer(data, 6);
            var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
            engine._unpackFlipY(true);
            ktx.uploadLevels(texture, texture.generateMipMaps);
            texture.width = ktx.pixelWidth;
            texture.height = ktx.pixelHeight;
            engine._setCubeMapTextureParams(loadMipmap);
            texture.isReady = true;
        };
        /**
         * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param callback defines the method to call once ready to upload
         */
        KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
            var ktx = new BABYLON.KhronosTextureContainer(data, 1);
            callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
                ktx.uploadLevels(texture, texture.generateMipMaps);
            });
        };
        return KTXTextureLoader;
    }());
    // Register the loader.
    BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.ktxTextureLoader.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Sets of helpers addressing the serialization and deserialization of environment texture
     * stored in a BabylonJS env file.
     * Those files are usually stored as .env files.
     */
    var EnvironmentTextureTools = /** @class */ (function () {
        function EnvironmentTextureTools() {
        }
        /**
         * Gets the environment info from an env file.
         * @param data The array buffer containing the .env bytes.
         * @returns the environment file info (the json header) if successfully parsed.
         */
        EnvironmentTextureTools.GetEnvInfo = function (data) {
            var dataView = new DataView(data);
            var pos = 0;
            for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
                if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
                    BABYLON.Tools.Error('Not a babylon environment map');
                    return null;
                }
            }
            // Read json manifest - collect characters up to null terminator
            var manifestString = '';
            var charCode = 0x00;
            while ((charCode = dataView.getUint8(pos++))) {
                manifestString += String.fromCharCode(charCode);
            }
            var manifest = JSON.parse(manifestString);
            if (manifest.specular) {
                // Extend the header with the position of the payload.
                manifest.specular.specularDataPosition = pos;
                // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
                manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
            }
            return manifest;
        };
        /**
         * Creates an environment texture from a loaded cube texture.
         * @param texture defines the cube texture to convert in env file
         * @return a promise containing the environment data if succesfull.
         */
        EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
            var _this = this;
            var internalTexture = texture.getInternalTexture();
            if (!internalTexture) {
                return Promise.reject("The cube texture is invalid.");
            }
            if (!texture._prefiltered) {
                return Promise.reject("The cube texture is invalid (not prefiltered).");
            }
            var engine = internalTexture.getEngine();
            if (engine && engine.premultipliedAlpha) {
                return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
            }
            if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
                return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
            }
            var canvas = engine.getRenderingCanvas();
            if (!canvas) {
                return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
            }
            var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
            if (!engine.getCaps().textureFloatRender) {
                textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
                if (!engine.getCaps().textureHalfFloatRender) {
                    return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
                }
            }
            var cubeWidth = internalTexture.width;
            var hostingScene = new BABYLON.Scene(engine);
            var specularTextures = {};
            var promises = [];
            // Read and collect all mipmaps data from the cube.
            var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
            mipmapsCount = Math.round(mipmapsCount);
            var _loop_1 = function (i) {
                var faceWidth = Math.pow(2, mipmapsCount - i);
                var _loop_2 = function (face) {
                    var data = texture.readPixels(face, i);
                    // Creates a temp texture with the face data.
                    var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
                    // And rgbdEncode them.
                    var promise = new Promise(function (resolve, reject) {
                        var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
                        rgbdPostProcess.getEffect().executeWhenCompiled(function () {
                            rgbdPostProcess.onApply = function (effect) {
                                effect._bindTexture("textureSampler", tempTexture);
                            };
                            // As the process needs to happen on the main canvas, keep track of the current size
                            var currentW = engine.getRenderWidth();
                            var currentH = engine.getRenderHeight();
                            // Set the desired size for the texture
                            engine.setSize(faceWidth, faceWidth);
                            hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
                            // Reading datas from WebGL
                            BABYLON.Tools.ToBlob(canvas, function (blob) {
                                var fileReader = new FileReader();
                                fileReader.onload = function (event) {
                                    var arrayBuffer = event.target.result;
                                    specularTextures[i * 6 + face] = arrayBuffer;
                                    resolve();
                                };
                                fileReader.readAsArrayBuffer(blob);
                            });
                            // Reapply the previous canvas size
                            engine.setSize(currentW, currentH);
                        });
                    });
                    promises.push(promise);
                };
                // All faces of the cube.
                for (var face = 0; face < 6; face++) {
                    _loop_2(face);
                }
            };
            for (var i = 0; i <= mipmapsCount; i++) {
                _loop_1(i);
            }
            // Once all the textures haves been collected as RGBD stored in PNGs
            return Promise.all(promises).then(function () {
                // We can delete the hosting scene keeping track of all the creation objects
                hostingScene.dispose();
                // Creates the json header for the env texture
                var info = {
                    version: 1,
                    width: cubeWidth,
                    irradiance: _this._CreateEnvTextureIrradiance(texture),
                    specular: {
                        mipmaps: [],
                        lodGenerationScale: texture.lodGenerationScale
                    }
                };
                // Sets the specular image data information
                var position = 0;
                for (var i = 0; i <= mipmapsCount; i++) {
                    for (var face = 0; face < 6; face++) {
                        var byteLength = specularTextures[i * 6 + face].byteLength;
                        info.specular.mipmaps.push({
                            length: byteLength,
                            position: position
                        });
                        position += byteLength;
                    }
                }
                // Encode the JSON as an array buffer
                var infoString = JSON.stringify(info);
                var infoBuffer = new ArrayBuffer(infoString.length + 1);
                var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
                for (var i = 0, strLen = infoString.length; i < strLen; i++) {
                    infoView[i] = infoString.charCodeAt(i);
                }
                // Ends up with a null terminator for easier parsing
                infoView[infoString.length] = 0x00;
                // Computes the final required size and creates the storage
                var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
                var finalBuffer = new ArrayBuffer(totalSize);
                var finalBufferView = new Uint8Array(finalBuffer);
                var dataView = new DataView(finalBuffer);
                // Copy the magic bytes identifying the file in
                var pos = 0;
                for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
                    dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
                }
                // Add the json info
                finalBufferView.set(new Uint8Array(infoBuffer), pos);
                pos += infoBuffer.byteLength;
                // Finally inserts the texture data
                for (var i = 0; i <= mipmapsCount; i++) {
                    for (var face = 0; face < 6; face++) {
                        var dataBuffer = specularTextures[i * 6 + face];
                        finalBufferView.set(new Uint8Array(dataBuffer), pos);
                        pos += dataBuffer.byteLength;
                    }
                }
                // Voila
                return finalBuffer;
            });
        };
        /**
         * Creates a JSON representation of the spherical data.
         * @param texture defines the texture containing the polynomials
         * @return the JSON representation of the spherical info
         */
        EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
            var polynmials = texture.sphericalPolynomial;
            if (polynmials == null) {
                return null;
            }
            return {
                x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
                y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
                z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
                xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
                yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
                zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
                yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
                zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
                xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
            };
        };
        /**
         * Uploads the texture info contained in the env file to the GPU.
         * @param texture defines the internal texture to upload to
         * @param arrayBuffer defines the buffer cotaining the data to load
         * @param info defines the texture info retrieved through the GetEnvInfo method
         * @returns a promise
         */
        EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
            if (info.version !== 1) {
                throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
            }
            var specularInfo = info.specular;
            if (!specularInfo) {
                // Nothing else parsed so far
                return Promise.resolve();
            }
            // Double checks the enclosed info
            var mipmapsCount = BABYLON.Scalar.Log2(info.width);
            mipmapsCount = Math.round(mipmapsCount) + 1;
            if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
                throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
            }
            texture._lodGenerationScale = specularInfo.lodGenerationScale;
            var imageData = new Array(mipmapsCount);
            for (var i = 0; i < mipmapsCount; i++) {
                imageData[i] = new Array(6);
                for (var face = 0; face < 6; face++) {
                    var imageInfo = specularInfo.mipmaps[i * 6 + face];
                    imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
                }
            }
            return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
        };
        /**
         * Uploads the levels of image data to the GPU.
         * @param texture defines the internal texture to upload to
         * @param imageData defines the array buffer views of image data [mipmap][face]
         * @returns a promise
         */
        EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
            if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
                throw new Error("Texture size must be a power of two");
            }
            var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
            // Gets everything ready.
            var engine = texture.getEngine();
            var expandTexture = false;
            var generateNonLODTextures = false;
            var rgbdPostProcess = null;
            var cubeRtt = null;
            var lodTextures = null;
            var caps = engine.getCaps();
            texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
            texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            texture.generateMipMaps = true;
            engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
            // Add extra process if texture lod is not supported
            if (!caps.textureLOD) {
                expandTexture = false;
                generateNonLODTextures = true;
                lodTextures = {};
            }
            // in webgl 1 there are no ways to either render or copy lod level information for float textures.
            else if (engine.webGLVersion < 2) {
                expandTexture = false;
            }
            // If half float available we can uncompress the texture
            else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
                expandTexture = true;
                texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
            }
            // If full float available we can uncompress the texture
            else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
                expandTexture = true;
                texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
            }
            // Expand the texture if possible
            if (expandTexture) {
                // Simply run through the decode PP
                rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
                texture._isRGBD = false;
                texture.invertY = false;
                cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
                    generateDepthBuffer: false,
                    generateMipMaps: true,
                    generateStencilBuffer: false,
                    samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
                    type: texture.type,
                    format: BABYLON.Engine.TEXTUREFORMAT_RGBA
                });
            }
            else {
                texture._isRGBD = true;
                texture.invertY = true;
                // In case of missing support, applies the same patch than DDS files.
                if (generateNonLODTextures) {
                    var mipSlices = 3;
                    var scale = texture._lodGenerationScale;
                    var offset = texture._lodGenerationOffset;
                    for (var i = 0; i < mipSlices; i++) {
                        //compute LOD from even spacing in smoothness (matching shader calculation)
                        var smoothness = i / (mipSlices - 1);
                        var roughness = 1 - smoothness;
                        var minLODIndex = offset; // roughness = 0
                        var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
                        var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
                        var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
                        var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
                        glTextureFromLod.isCube = true;
                        glTextureFromLod.invertY = true;
                        glTextureFromLod.generateMipMaps = false;
                        engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
                        // Wrap in a base texture for easy binding.
                        var lodTexture = new BABYLON.BaseTexture(null);
                        lodTexture.isCube = true;
                        lodTexture._texture = glTextureFromLod;
                        lodTextures[mipmapIndex] = lodTexture;
                        switch (i) {
                            case 0:
                                texture._lodTextureLow = lodTexture;
                                break;
                            case 1:
                                texture._lodTextureMid = lodTexture;
                                break;
                            case 2:
                                texture._lodTextureHigh = lodTexture;
                                break;
                        }
                    }
                }
            }
            var promises = [];
            var _loop_3 = function (i) {
                var _loop_4 = function (face) {
                    // Constructs an image element from image data
                    var bytes = imageData[i][face];
                    var blob = new Blob([bytes], { type: 'image/png' });
                    var url = URL.createObjectURL(blob);
                    var image = new Image();
                    image.src = url;
                    // Enqueue promise to upload to the texture.
                    var promise = new Promise(function (resolve, reject) {
                        image.onload = function () {
                            if (expandTexture) {
                                var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
                                    reject(message);
                                }, image);
                                rgbdPostProcess.getEffect().executeWhenCompiled(function () {
                                    // Uncompress the data to a RTT
                                    rgbdPostProcess.onApply = function (effect) {
                                        effect._bindTexture("textureSampler", tempTexture_1);
                                        effect.setFloat2("scale", 1, 1);
                                    };
                                    engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
                                    // Cleanup
                                    engine.restoreDefaultFramebuffer();
                                    tempTexture_1.dispose();
                                    window.URL.revokeObjectURL(url);
                                    resolve();
                                });
                            }
                            else {
                                engine._uploadImageToTexture(texture, image, face, i);
                                // Upload the face to the non lod texture support
                                if (generateNonLODTextures) {
                                    var lodTexture = lodTextures[i];
                                    if (lodTexture) {
                                        engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
                                    }
                                }
                                resolve();
                            }
                        };
                        image.onerror = function (error) {
                            reject(error);
                        };
                    });
                    promises.push(promise);
                };
                // All faces
                for (var face = 0; face < 6; face++) {
                    _loop_4(face);
                }
            };
            // All mipmaps up to provided number of images
            for (var i = 0; i < imageData.length; i++) {
                _loop_3(i);
            }
            // Fill remaining mipmaps with black textures.
            if (imageData.length < mipmapsCount) {
                var data = void 0;
                var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
                var dataLength = size * size * 4;
                switch (texture.type) {
                    case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
                        data = new Uint8Array(dataLength);
                        break;
                    }
                    case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
                        data = new Uint16Array(dataLength);
                        break;
                    }
                    case BABYLON.Engine.TEXTURETYPE_FLOAT: {
                        data = new Float32Array(dataLength);
                        break;
                    }
                }
                for (var i = imageData.length; i < mipmapsCount; i++) {
                    for (var face = 0; face < 6; face++) {
                        engine._uploadArrayBufferViewToTexture(texture, data, face, i);
                    }
                }
            }
            // Once all done, finishes the cleanup and return
            return Promise.all(promises).then(function () {
                // Release temp RTT.
                if (cubeRtt) {
                    engine._releaseFramebufferObjects(cubeRtt);
                    cubeRtt._swapAndDie(texture);
                }
                // Release temp Post Process.
                if (rgbdPostProcess) {
                    rgbdPostProcess.dispose();
                }
                // Flag internal texture as ready in case they are in use.
                if (generateNonLODTextures) {
                    if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
                        texture._lodTextureHigh._texture.isReady = true;
                    }
                    if (texture._lodTextureMid && texture._lodTextureMid._texture) {
                        texture._lodTextureMid._texture.isReady = true;
                    }
                    if (texture._lodTextureLow && texture._lodTextureLow._texture) {
                        texture._lodTextureLow._texture.isReady = true;
                    }
                }
            });
        };
        /**
         * Uploads spherical polynomials information to the texture.
         * @param texture defines the texture we are trying to upload the information to
         * @param info defines the environment texture info retrieved through the GetEnvInfo method
         */
        EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
            if (info.version !== 1) {
                BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
            }
            var irradianceInfo = info.irradiance;
            if (!irradianceInfo) {
                return;
            }
            var sp = new BABYLON.SphericalPolynomial();
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
            BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
            texture._sphericalPolynomial = sp;
        };
        /**
         * Magic number identifying the env file.
         */
        EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
        return EnvironmentTextureTools;
    }());
    BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.environmentTextureTools.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Implementation of the ENV Texture Loader.
     */
    var ENVTextureLoader = /** @class */ (function () {
        function ENVTextureLoader() {
            /**
             * Defines wether the loader supports cascade loading the different faces.
             */
            this.supportCascades = false;
        }
        /**
         * This returns if the loader support the current file information.
         * @param extension defines the file extension of the file being loaded
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @param fallback defines the fallback internal texture if any
         * @param isBase64 defines whether the texture is encoded as a base64
         * @param isBuffer defines whether the texture data are stored as a buffer
         * @returns true if the loader can load the specified file
         */
        ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
            return extension.indexOf(".env") === 0;
        };
        /**
         * Transform the url before loading if required.
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the transformed texture
         */
        ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
            return rootUrl;
        };
        /**
         * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
         * @param rootUrl the url of the texture
         * @param textureFormatInUse defines the current compressed format in use iun the engine
         * @returns the fallback texture
         */
        ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
            return null;
        };
        /**
         * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param createPolynomials will be true if polynomials have been requested
         * @param onLoad defines the callback to trigger once the texture is ready
         * @param onError defines the callback to trigger in case of error
         */
        ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
            if (Array.isArray(data)) {
                return;
            }
            data = data;
            var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
            if (info) {
                texture.width = info.width;
                texture.height = info.width;
                BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
                BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
                    texture.isReady = true;
                    if (onLoad) {
                        onLoad();
                    }
                });
            }
            else if (onError) {
                onError("Can not parse the environment file", null);
            }
        };
        /**
         * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
         * @param data contains the texture data
         * @param texture defines the BabylonJS internal texture
         * @param callback defines the method to call once ready to upload
         */
        ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
            throw ".env not supported in 2d.";
        };
        return ENVTextureLoader;
    }());
    // Register the loader.
    BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.envTextureLoader.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Renders a layer on top of an existing scene
     */
    var UtilityLayerRenderer = /** @class */ (function () {
        /**
         * Instantiates a UtilityLayerRenderer
         * @param originalScene the original scene that will be rendered on top of
         */
        function UtilityLayerRenderer(
        /** the original scene that will be rendered on top of */
        originalScene) {
            var _this = this;
            this.originalScene = originalScene;
            this._pointerCaptures = {};
            this._lastPointerEvents = {};
            /**
             *  If the utility layer should automatically be rendered on top of existing scene
            */
            this.shouldRender = true;
            /**
             * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
             */
            this.onlyCheckPointerDownEvents = true;
            /**
             * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
             */
            this.processAllEvents = false;
            /**
             * Observable raised when the pointer move from the utility layer scene to the main scene
             */
            this.onPointerOutObservable = new BABYLON.Observable();
            // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
            this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
            this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
            this.utilityLayerScene._allowPostProcessClearColor = false;
            originalScene.getEngine().scenes.pop();
            // Detach controls on utility scene, events will be fired by logic below to handle picking priority
            this.utilityLayerScene.detachControl();
            this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
                if (!_this.processAllEvents) {
                    if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
                        && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
                        && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
                        return;
                    }
                }
                var pointerEvent = (prePointerInfo.event);
                if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
                    _this._pointerCaptures[pointerEvent.pointerId] = false;
                    return;
                }
                var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
                if (!prePointerInfo.ray && utilityScenePick) {
                    prePointerInfo.ray = utilityScenePick.ray;
                }
                // always fire the prepointer oversvable
                _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
                // allow every non pointer down event to flow to the utility layer
                if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
                    if (!prePointerInfo.skipOnPointerObservable) {
                        _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
                    }
                    if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
                        _this._pointerCaptures[pointerEvent.pointerId] = false;
                    }
                    return;
                }
                if (_this.utilityLayerScene.autoClearDepthAndStencil) {
                    // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
                    if (utilityScenePick && utilityScenePick.hit) {
                        if (!prePointerInfo.skipOnPointerObservable) {
                            _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
                        }
                        prePointerInfo.skipOnPointerObservable = true;
                    }
                }
                else {
                    var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
                    var pointerEvent_1 = (prePointerInfo.event);
                    // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
                    if (originalScenePick && utilityScenePick) {
                        // No pick in utility scene
                        if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
                            if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
                                // We touched an utility mesh present in the main scene
                                _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
                                prePointerInfo.skipOnPointerObservable = true;
                            }
                            else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                                _this._pointerCaptures[pointerEvent_1.pointerId] = true;
                            }
                            else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
                                // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
                                _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
                                delete _this._lastPointerEvents[pointerEvent_1.pointerId];
                            }
                        }
                        else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
                            // We pick something in utility scene or the pick in utility is closer than the one in main scene
                            _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
                            // If a previous utility layer set this, do not unset this
                            if (!prePointerInfo.skipOnPointerObservable) {
                                prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
                            }
                        }
                        else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
                            // We have a pick in both scenes but main is closer than utility
                            // We touched an utility mesh present in the main scene
                            if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
                                _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
                                prePointerInfo.skipOnPointerObservable = true;
                            }
                            else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
                                // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
                                _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
                                delete _this._lastPointerEvents[pointerEvent_1.pointerId];
                            }
                        }
                        if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
                            _this._pointerCaptures[pointerEvent_1.pointerId] = false;
                        }
                    }
                }
            });
            // Render directly on top of existing scene without clearing
            this.utilityLayerScene.autoClear = false;
            this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
                if (_this.shouldRender) {
                    _this.render();
                }
            });
            this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
                _this.dispose();
            });
            this._updateCamera();
        }
        Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
            /**
             * A shared utility layer that can be used to overlay objects into a scene (Depth map of the previous scene is cleared before drawing on top of it)
             */
            get: function () {
                if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
                    UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
                    UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
                        UtilityLayerRenderer._DefaultUtilityLayer = null;
                    });
                }
                return UtilityLayerRenderer._DefaultUtilityLayer;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
            /**
             * A shared utility layer that can be used to embed objects into a scene (Depth map of the previous scene is not cleared before drawing on top of it)
             */
            get: function () {
                if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
                    UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
                    UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
                    UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
                        UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
                    });
                }
                return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
            },
            enumerable: true,
            configurable: true
        });
        UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
            if (!prePointerInfo.skipOnPointerObservable) {
                this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
                this._lastPointerEvents[pointerEvent.pointerId] = true;
            }
        };
        /**
         * Renders the utility layers scene on top of the original scene
         */
        UtilityLayerRenderer.prototype.render = function () {
            this._updateCamera();
            if (this.utilityLayerScene.activeCamera) {
                // Set the camera's scene to utility layers scene
                var oldScene = this.utilityLayerScene.activeCamera.getScene();
                var camera = this.utilityLayerScene.activeCamera;
                camera._scene = this.utilityLayerScene;
                if (camera.leftCamera) {
                    camera.leftCamera._scene = this.utilityLayerScene;
                }
                if (camera.rightCamera) {
                    camera.rightCamera._scene = this.utilityLayerScene;
                }
                this.utilityLayerScene.render(false);
                // Reset camera's scene back to original
                camera._scene = oldScene;
                if (camera.leftCamera) {
                    camera.leftCamera._scene = oldScene;
                }
                if (camera.rightCamera) {
                    camera.rightCamera._scene = oldScene;
                }
            }
        };
        /**
         * Disposes of the renderer
         */
        UtilityLayerRenderer.prototype.dispose = function () {
            this.onPointerOutObservable.clear();
            if (this._afterRenderObserver) {
                this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
            }
            if (this._sceneDisposeObserver) {
                this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
            }
            if (this._originalPointerObserver) {
                this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
            }
            this.utilityLayerScene.dispose();
        };
        UtilityLayerRenderer.prototype._updateCamera = function () {
            this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
        };
        UtilityLayerRenderer._DefaultUtilityLayer = null;
        UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
        return UtilityLayerRenderer;
    }());
    BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.utilityLayerRenderer.js.map



//# sourceMappingURL=babylon.behavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
     */
    var PointerDragBehavior = /** @class */ (function () {
        /**
         * Creates a pointer drag behavior that can be attached to a mesh
         * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
         */
        function PointerDragBehavior(options) {
            /**
             * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0)
             */
            this.maxDragAngle = 0;
            /**
             * @hidden
             */
            this._useAlternatePickedPointAboveMaxDragAngle = false;
            /**
             * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
             */
            this.currentDraggingPointerID = -1;
            /**
             * If the behavior is currently in a dragging state
             */
            this.dragging = false;
            /**
             * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
             */
            this.dragDeltaRatio = 0.2;
            /**
             * If the drag plane orientation should be updated during the dragging (Default: true)
             */
            this.updateDragPlane = true;
            // Debug mode will display drag planes to help visualize behavior
            this._debugMode = false;
            this._moving = false;
            /**
             *  Fires each time the attached mesh is dragged with the pointer
             *  * delta between last drag position and current drag position in world space
             *  * dragDistance along the drag axis
             *  * dragPlaneNormal normal of the current drag plane used during the drag
             *  * dragPlanePoint in world space where the drag intersects the drag plane
             */
            this.onDragObservable = new BABYLON.Observable();
            /**
             *  Fires each time a drag begins (eg. mouse down on mesh)
             */
            this.onDragStartObservable = new BABYLON.Observable();
            /**
             *  Fires each time a drag ends (eg. mouse release after drag)
             */
            this.onDragEndObservable = new BABYLON.Observable();
            /**
             *  If the attached mesh should be moved when dragged
             */
            this.moveAttached = true;
            /**
             *  If the drag behavior will react to drag events (Default: true)
             */
            this.enabled = true;
            /**
             * If camera controls should be detached during the drag
             */
            this.detachCameraControls = true;
            /**
             * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
             */
            this.useObjectOrienationForDragging = true;
            this._tmpVector = new BABYLON.Vector3(0, 0, 0);
            this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
            this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
            this._targetPosition = new BABYLON.Vector3(0, 0, 0);
            this._attachedElement = null;
            this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
            this._lastPointerRay = {};
            this._dragDelta = new BABYLON.Vector3();
            // Variables to avoid instantiation in the below method
            this._pointA = new BABYLON.Vector3(0, 0, 0);
            this._pointB = new BABYLON.Vector3(0, 0, 0);
            this._pointC = new BABYLON.Vector3(0, 0, 0);
            this._lineA = new BABYLON.Vector3(0, 0, 0);
            this._lineB = new BABYLON.Vector3(0, 0, 0);
            this._localAxis = new BABYLON.Vector3(0, 0, 0);
            this._lookAt = new BABYLON.Vector3(0, 0, 0);
            this._options = options ? options : {};
            var optionCount = 0;
            if (this._options.dragAxis) {
                optionCount++;
            }
            if (this._options.dragPlaneNormal) {
                optionCount++;
            }
            if (optionCount > 1) {
                throw "Multiple drag modes specified in dragBehavior options. Only one expected";
            }
        }
        Object.defineProperty(PointerDragBehavior.prototype, "name", {
            /**
             *  The name of the behavior
             */
            get: function () {
                return "PointerDrag";
            },
            enumerable: true,
            configurable: true
        });
        /**
         *  Initializes the behavior
         */
        PointerDragBehavior.prototype.init = function () { };
        /**
         * Attaches the drag behavior the passed in mesh
         * @param ownerNode The mesh that will be dragged around once attached
         */
        PointerDragBehavior.prototype.attach = function (ownerNode) {
            var _this = this;
            this._scene = ownerNode.getScene();
            this._attachedNode = ownerNode;
            // Initialize drag plane to not interfere with existing scene
            if (!PointerDragBehavior._planeScene) {
                if (this._debugMode) {
                    PointerDragBehavior._planeScene = this._scene;
                }
                else {
                    PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
                    PointerDragBehavior._planeScene.detachControl();
                    this._scene.getEngine().scenes.pop();
                    this._scene.onDisposeObservable.addOnce(function () {
                        PointerDragBehavior._planeScene.dispose();
                        PointerDragBehavior._planeScene = null;
                    });
                }
            }
            this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
            // State of the drag
            this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
            var pickPredicate = function (m) {
                return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
            };
            this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
                if (!_this.enabled) {
                    return;
                }
                if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
                    if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
                        _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
                    }
                }
                else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
                    if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
                        _this.releaseDrag();
                    }
                }
                else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
                    var pointerId = pointerInfo.event.pointerId;
                    // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
                    if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
                        if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
                            _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
                            delete _this._lastPointerRay[_this.currentDraggingPointerID];
                        }
                        _this.currentDraggingPointerID = pointerId;
                    }
                    // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
                    if (!_this._lastPointerRay[pointerId]) {
                        _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
                    }
                    if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
                        _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
                        _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
                        if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
                            _this._moveDrag(pointerInfo.pickInfo.ray);
                        }
                    }
                }
            });
            this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
                if (_this._moving && _this.moveAttached) {
                    BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
                    // Slowly move mesh to avoid jitter
                    _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
                    _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
                    (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
                    (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
                    BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
                }
            });
        };
        /**
         * Force relase the drag action by code.
         */
        PointerDragBehavior.prototype.releaseDrag = function () {
            this.dragging = false;
            this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
            this.currentDraggingPointerID = -1;
            this._moving = false;
            // Reattach camera controls
            if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
                this._scene.activeCamera.attachControl(this._attachedElement, true);
            }
        };
        /**
         * Simulates the start of a pointer drag event on the behavior
         * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
         * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
         * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
         */
        PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
            if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
            this._startDrag(pointerId, fromRay, startPickedPoint);
            var lastRay = this._lastPointerRay[pointerId];
            if (pointerId === PointerDragBehavior._AnyMouseID) {
                lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
            }
            if (lastRay) {
                // if there was a last pointer ray drag the object there
                this._moveDrag(lastRay);
            }
        };
        PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
            if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
                return;
            }
            BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
            // Create start ray from the camera to the object
            if (fromRay) {
                this._startDragRay.direction.copyFrom(fromRay.direction);
                this._startDragRay.origin.copyFrom(fromRay.origin);
            }
            else {
                this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
                this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
                this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
            }
            this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
            var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
            if (pickedPoint) {
                this.dragging = true;
                this.currentDraggingPointerID = pointerId;
                this.lastDragPosition.copyFrom(pickedPoint);
                this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
                this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
                // Detatch camera controls
                if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
                    if (this._scene.activeCamera.inputs.attachedElement) {
                        this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
                        this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
                    }
                    else {
                        this._attachedElement = null;
                    }
                }
            }
            BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
        };
        PointerDragBehavior.prototype._moveDrag = function (ray) {
            this._moving = true;
            var pickedPoint = this._pickWithRayOnDragPlane(ray);
            if (pickedPoint) {
                if (this.updateDragPlane) {
                    this._updateDragPlanePosition(ray, pickedPoint);
                }
                var dragLength = 0;
                // depending on the drag mode option drag accordingly
                if (this._options.dragAxis) {
                    // Convert local drag axis to world
                    BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
                    // Project delta drag from the drag plane onto the drag axis
                    pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
                    dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
                    this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
                }
                else {
                    dragLength = this._dragDelta.length();
                    pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
                }
                this._targetPosition.addInPlace(this._dragDelta);
                this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
                this.lastDragPosition.copyFrom(pickedPoint);
            }
        };
        PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
            var _this = this;
            if (!ray) {
                return null;
            }
            // Calculate angle between plane normal and ray
            var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
            // Correct if ray is casted from oposite side
            if (angle > Math.PI / 2) {
                angle = Math.PI - angle;
            }
            // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
            if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
                if (this._useAlternatePickedPointAboveMaxDragAngle) {
                    // Invert ray direction along the towards object axis
                    this._tmpVector.copyFrom(ray.direction);
                    (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
                    this._alternatePickedPoint.normalize();
                    this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
                    this._tmpVector.addInPlace(this._alternatePickedPoint);
                    // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
                    var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
                    this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
                    this._alternatePickedPoint.addInPlace(this._tmpVector);
                    this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
                    return this._alternatePickedPoint;
                }
                else {
                    return null;
                }
            }
            var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
            if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
                return pickResult.pickedPoint;
            }
            else {
                return null;
            }
        };
        // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
        PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
            this._pointA.copyFrom(dragPlanePosition);
            if (this._options.dragAxis) {
                this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
                // Calculate plane normal in direction of camera but perpendicular to drag axis
                this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
                ray.origin.subtractToRef(this._pointA, this._pointC);
                this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
                // Get perpendicular line from direction to camera and drag axis
                this._pointB.subtractToRef(this._pointA, this._lineA);
                this._pointC.subtractToRef(this._pointA, this._lineB);
                BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
                // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
                BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
                this._lookAt.normalize();
                this._dragPlane.position.copyFrom(this._pointA);
                this._pointA.subtractToRef(this._lookAt, this._lookAt);
                this._dragPlane.lookAt(this._lookAt);
            }
            else if (this._options.dragPlaneNormal) {
                this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
                this._dragPlane.position.copyFrom(this._pointA);
                this._pointA.subtractToRef(this._localAxis, this._lookAt);
                this._dragPlane.lookAt(this._lookAt);
            }
            else {
                this._dragPlane.position.copyFrom(this._pointA);
                this._dragPlane.lookAt(ray.origin);
            }
            this._dragPlane.computeWorldMatrix(true);
        };
        /**
         *  Detaches the behavior from the mesh
         */
        PointerDragBehavior.prototype.detach = function () {
            if (this._pointerObserver) {
                this._scene.onPointerObservable.remove(this._pointerObserver);
            }
            if (this._beforeRenderObserver) {
                this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
            }
        };
        PointerDragBehavior._AnyMouseID = -2;
        return PointerDragBehavior;
    }());
    BABYLON.PointerDragBehavior = PointerDragBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.pointerDragBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A behavior that when attached to a mesh will allow the mesh to be scaled
     */
    var MultiPointerScaleBehavior = /** @class */ (function () {
        /**
         * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
         */
        function MultiPointerScaleBehavior() {
            this._startDistance = 0;
            this._initialScale = new BABYLON.Vector3(0, 0, 0);
            this._targetScale = new BABYLON.Vector3(0, 0, 0);
            this._sceneRenderObserver = null;
            this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
            this._dragBehaviorA.moveAttached = false;
            this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
            this._dragBehaviorB.moveAttached = false;
        }
        Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
            /**
             *  The name of the behavior
             */
            get: function () {
                return "MultiPointerScale";
            },
            enumerable: true,
            configurable: true
        });
        /**
         *  Initializes the behavior
         */
        MultiPointerScaleBehavior.prototype.init = function () { };
        MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
            return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
        };
        /**
         * Attaches the scale behavior the passed in mesh
         * @param ownerNode The mesh that will be scaled around once attached
         */
        MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
            var _this = this;
            this._ownerNode = ownerNode;
            // Create 2 drag behaviors such that each will only be triggered by a separate pointer
            this._dragBehaviorA.onDragStartObservable.add(function (e) {
                if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
                    if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
                        _this._dragBehaviorA.releaseDrag();
                    }
                    else {
                        _this._initialScale.copyFrom(ownerNode.scaling);
                        _this._startDistance = _this._getCurrentDistance();
                    }
                }
            });
            this._dragBehaviorB.onDragStartObservable.add(function (e) {
                if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
                    if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
                        _this._dragBehaviorB.releaseDrag();
                    }
                    else {
                        _this._initialScale.copyFrom(ownerNode.scaling);
                        _this._startDistance = _this._getCurrentDistance();
                    }
                }
            });
            // Once both drag behaviors are active scale based on the distance between the two pointers
            [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
                behavior.onDragObservable.add(function () {
                    if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
                        var ratio = _this._getCurrentDistance() / _this._startDistance;
                        _this._initialScale.scaleToRef(ratio, _this._targetScale);
                    }
                });
            });
            ownerNode.addBehavior(this._dragBehaviorA);
            ownerNode.addBehavior(this._dragBehaviorB);
            // On every frame move towards target scaling to avoid jitter caused by vr controllers
            this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
                if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
                    var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
                    if (change.length() > 0.01) {
                        ownerNode.scaling.addInPlace(change);
                    }
                }
            });
        };
        /**
         *  Detaches the behavior from the mesh
         */
        MultiPointerScaleBehavior.prototype.detach = function () {
            var _this = this;
            this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
            [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
                behavior.onDragStartObservable.clear();
                behavior.onDragObservable.clear();
                _this._ownerNode.removeBehavior(behavior);
            });
        };
        return MultiPointerScaleBehavior;
    }());
    BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
     */
    var SixDofDragBehavior = /** @class */ (function () {
        /**
         * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
         */
        function SixDofDragBehavior() {
            this._sceneRenderObserver = null;
            this._targetPosition = new BABYLON.Vector3(0, 0, 0);
            this._moving = false;
            this._startingOrientation = new BABYLON.Quaternion();
            /**
             * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3)
             */
            this.zDragFactor = 3;
            /**
             * If the behavior is currently in a dragging state
             */
            this.dragging = false;
            /**
             * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
             */
            this.dragDeltaRatio = 0.2;
            /**
             * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
             */
            this.currentDraggingPointerID = -1;
            /**
             * If camera controls should be detached during the drag
             */
            this.detachCameraControls = true;
            /**
             * Fires each time a drag starts
             */
            this.onDragStartObservable = new BABYLON.Observable();
            /**
             *  Fires each time a drag ends (eg. mouse release after drag)
             */
            this.onDragEndObservable = new BABYLON.Observable();
        }
        Object.defineProperty(SixDofDragBehavior.prototype, "name", {
            /**
             *  The name of the behavior
             */
            get: function () {
                return "SixDofDrag";
            },
            enumerable: true,
            configurable: true
        });
        /**
         *  Initializes the behavior
         */
        SixDofDragBehavior.prototype.init = function () { };
        /**
         * Attaches the scale behavior the passed in mesh
         * @param ownerNode The mesh that will be scaled around once attached
         */
        SixDofDragBehavior.prototype.attach = function (ownerNode) {
            var _this = this;
            this._ownerNode = ownerNode;
            this._scene = this._ownerNode.getScene();
            if (!SixDofDragBehavior._virtualScene) {
                SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
                SixDofDragBehavior._virtualScene.detachControl();
                this._scene.getEngine().scenes.pop();
            }
            var pickedMesh = null;
            var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
            // Setup virtual meshes to be used for dragging without dirtying the existing scene
            this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
            this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
            this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
            this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
            var pickPredicate = function (m) {
                return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
            };
            var attachedElement = null;
            this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
                if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
                    if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
                        if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
                            pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
                        }
                        pickedMesh = _this._ownerNode;
                        BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
                        lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
                        // Set position and orientation of the controller
                        _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
                        _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
                        // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
                        _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
                        pickedMesh.computeWorldMatrix();
                        _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
                        if (!pickedMesh.rotationQuaternion) {
                            pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
                        }
                        var oldParent = pickedMesh.parent;
                        pickedMesh.setParent(null);
                        _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
                        pickedMesh.setParent(oldParent);
                        _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
                        // Update state
                        _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
                        _this.dragging = true;
                        _this.currentDraggingPointerID = pointerInfo.event.pointerId;
                        // Detatch camera controls
                        if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
                            if (_this._scene.activeCamera.inputs.attachedElement) {
                                attachedElement = _this._scene.activeCamera.inputs.attachedElement;
                                _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
                            }
                            else {
                                attachedElement = null;
                            }
                        }
                        BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
                        _this.onDragStartObservable.notifyObservers({});
                    }
                }
                else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
                    if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
                        _this.dragging = false;
                        _this._moving = false;
                        _this.currentDraggingPointerID = -1;
                        pickedMesh = null;
                        _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
                        // Reattach camera controls
                        if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
                            _this._scene.activeCamera.attachControl(attachedElement, true);
                        }
                        _this.onDragEndObservable.notifyObservers({});
                    }
                }
                else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
                    if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
                        var zDragFactor = _this.zDragFactor;
                        if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
                            pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
                            zDragFactor = 0;
                        }
                        // Calculate controller drag distance in controller space
                        var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
                        lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
                        var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
                        _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
                        // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
                        _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
                        if (_this._virtualDragMesh.position.z < 0) {
                            _this._virtualDragMesh.position.z = 0;
                        }
                        // Update the controller position
                        _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
                        _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
                        _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
                        // Move the virtualObjectsPosition into the picked mesh's space if needed
                        _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
                        if (pickedMesh.parent) {
                            BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
                        }
                        if (!_this._moving) {
                            _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
                        }
                        _this._moving = true;
                    }
                }
            });
            var tmpQuaternion = new BABYLON.Quaternion();
            // On every frame move towards target scaling to avoid jitter caused by vr controllers
            this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
                if (_this.dragging && _this._moving && pickedMesh) {
                    BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
                    // Slowly move mesh to avoid jitter
                    pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
                    // Get change in rotation
                    tmpQuaternion.copyFrom(_this._startingOrientation);
                    tmpQuaternion.x = -tmpQuaternion.x;
                    tmpQuaternion.y = -tmpQuaternion.y;
                    tmpQuaternion.z = -tmpQuaternion.z;
                    _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
                    // Convert change in rotation to only y axis rotation
                    BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
                    tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
                    // Slowly move mesh to avoid jitter
                    var oldParent = pickedMesh.parent;
                    pickedMesh.setParent(null);
                    BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
                    pickedMesh.setParent(oldParent);
                    BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
                }
            });
        };
        /**
         *  Detaches the behavior from the mesh
         */
        SixDofDragBehavior.prototype.detach = function () {
            if (this._scene) {
                this._scene.onPointerObservable.remove(this._pointerObserver);
            }
            if (this._ownerNode) {
                this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
            }
            if (this._virtualOriginMesh) {
                this._virtualOriginMesh.dispose();
            }
            if (this._virtualDragMesh) {
                this._virtualDragMesh.dispose();
            }
            this.onDragEndObservable.clear();
            this.onDragStartObservable.clear();
        };
        return SixDofDragBehavior;
    }());
    BABYLON.SixDofDragBehavior = SixDofDragBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sixDofDragBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     */
    var FaceDirectionInfo = /** @class */ (function () {
        function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
            if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
            if (diff === void 0) { diff = 0; }
            if (ignore === void 0) { ignore = false; }
            this.direction = direction;
            this.rotatedDirection = rotatedDirection;
            this.diff = diff;
            this.ignore = ignore;
        }
        return FaceDirectionInfo;
    }());
    /**
     * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
     */
    var AttachToBoxBehavior = /** @class */ (function () {
        /**
         * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
         * @param ui The transform node that should be attched to the mesh
         */
        function AttachToBoxBehavior(ui) {
            this.ui = ui;
            /**
             *  The name of the behavior
             */
            this.name = "AttachToBoxBehavior";
            /**
             * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
             */
            this.distanceAwayFromFace = 0.15;
            /**
             * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
             */
            this.distanceAwayFromBottomOfFace = 0.15;
            this._faceVectors = [new FaceDirectionInfo(BABYLON.Vector3.Up()), new FaceDirectionInfo(BABYLON.Vector3.Down()), new FaceDirectionInfo(BABYLON.Vector3.Left()), new FaceDirectionInfo(BABYLON.Vector3.Right()), new FaceDirectionInfo(BABYLON.Vector3.Forward()), new FaceDirectionInfo(BABYLON.Vector3.Forward().scaleInPlace(-1))];
            this._tmpMatrix = new BABYLON.Matrix();
            this._tmpVector = new BABYLON.Vector3();
            this._zeroVector = BABYLON.Vector3.Zero();
            this._lookAtTmpMatrix = new BABYLON.Matrix();
            /* Does nothing */
        }
        /**
         *  Initializes the behavior
         */
        AttachToBoxBehavior.prototype.init = function () {
            /* Does nothing */
        };
        AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
            var _this = this;
            // Go over each face and calculate the angle between the face's normal and targetDirection
            this._faceVectors.forEach(function (v) {
                if (!_this._target.rotationQuaternion) {
                    _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
                }
                _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
                BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
                v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
            });
            // Return the face information of the one with the normal closeset to target direction
            return this._faceVectors.reduce(function (min, p) {
                if (min.ignore) {
                    return p;
                }
                else if (p.ignore) {
                    return min;
                }
                else {
                    return min.diff < p.diff ? min : p;
                }
            }, this._faceVectors[0]);
        };
        AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
            if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
            BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
            this._lookAtTmpMatrix.invert();
            BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
        };
        /**
         * Attaches the AttachToBoxBehavior to the passed in mesh
         * @param target The mesh that the specified node will be attached to
         */
        AttachToBoxBehavior.prototype.attach = function (target) {
            var _this = this;
            this._target = target;
            this._scene = this._target.getScene();
            // Every frame, update the app bars position
            this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
                if (!_this._scene.activeCamera) {
                    return;
                }
                // Find the face closest to the cameras position
                var cameraPos = _this._scene.activeCamera.position;
                if (_this._scene.activeCamera.devicePosition) {
                    cameraPos = _this._scene.activeCamera.devicePosition;
                }
                var facing = _this._closestFace(cameraPos.subtract(target.position));
                if (_this._scene.activeCamera.leftCamera) {
                    _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
                }
                else {
                    _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
                }
                // Get camera up direction
                BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
                // Ignore faces to not select a parrelel face for the up vector of the UI
                _this._faceVectors.forEach(function (v) {
                    if (facing.direction.x && v.direction.x) {
                        v.ignore = true;
                    }
                    if (facing.direction.y && v.direction.y) {
                        v.ignore = true;
                    }
                    if (facing.direction.z && v.direction.z) {
                        v.ignore = true;
                    }
                });
                var facingUp = _this._closestFace(_this._tmpVector);
                // Unignore faces
                _this._faceVectors.forEach(function (v) {
                    v.ignore = false;
                });
                // Position the app bar on that face
                _this.ui.position.copyFrom(target.position);
                if (facing.direction.x) {
                    facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
                    _this.ui.position.addInPlace(_this._tmpVector);
                }
                if (facing.direction.y) {
                    facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
                    _this.ui.position.addInPlace(_this._tmpVector);
                }
                if (facing.direction.z) {
                    facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
                    _this.ui.position.addInPlace(_this._tmpVector);
                }
                // Rotate to be oriented properly to the camera
                if (!_this.ui.rotationQuaternion) {
                    _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
                }
                facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
                _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
                // Place ui the correct distance from the bottom of the mesh
                if (facingUp.direction.x) {
                    _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
                }
                if (facingUp.direction.y) {
                    _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
                }
                if (facingUp.direction.z) {
                    _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
                }
                _this.ui.position.addInPlace(_this._tmpVector);
            });
        };
        /**
         *  Detaches the behavior from the mesh
         */
        AttachToBoxBehavior.prototype.detach = function () {
            this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
        };
        return AttachToBoxBehavior;
    }());
    BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.attachToBoxBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * A behavior that when attached to a mesh will allow the mesh to fade in and out
     */
    var FadeInOutBehavior = /** @class */ (function () {
        /**
         * Instatiates the FadeInOutBehavior
         */
        function FadeInOutBehavior() {
            var _this = this;
            /**
             * Time in milliseconds to delay before fading in (Default: 0)
             */
            this.delay = 0;
            /**
             * Time in milliseconds for the mesh to fade in (Default: 300)
             */
            this.fadeInTime = 300;
            this._millisecondsPerFrame = 1000 / 60;
            this._hovered = false;
            this._hoverValue = 0;
            this._ownerNode = null;
            this._update = function () {
                if (_this._ownerNode) {
                    _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
                    _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
                    if (_this._ownerNode.visibility > 1) {
                        _this._setAllVisibility(_this._ownerNode, 1);
                        _this._hoverValue = _this.fadeInTime + _this.delay;
                        return;
                    }
                    else if (_this._ownerNode.visibility < 0) {
                        _this._setAllVisibility(_this._ownerNode, 0);
                        if (_this._hoverValue < 0) {
                            _this._hoverValue = 0;
                            return;
                        }
                    }
                    setTimeout(_this._update, _this._millisecondsPerFrame);
                }
            };
        }
        Object.defineProperty(FadeInOutBehavior.prototype, "name", {
            /**
             *  The name of the behavior
             */
            get: function () {
                return "FadeInOut";
            },
            enumerable: true,
            configurable: true
        });
        /**
         *  Initializes the behavior
         */
        FadeInOutBehavior.prototype.init = function () {
        };
        /**
         * Attaches the fade behavior on the passed in mesh
         * @param ownerNode The mesh that will be faded in/out once attached
         */
        FadeInOutBehavior.prototype.attach = function (ownerNode) {
            this._ownerNode = ownerNode;
            this._setAllVisibility(this._ownerNode, 0);
        };
        /**
         *  Detaches the behavior from the mesh
         */
        FadeInOutBehavior.prototype.detach = function () {
            this._ownerNode = null;
        };
        /**
         * Triggers the mesh to begin fading in or out
         * @param value if the object should fade in or out (true to fade in)
         */
        FadeInOutBehavior.prototype.fadeIn = function (value) {
            this._hovered = value;
            this._update();
        };
        FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
            var _this = this;
            mesh.visibility = value;
            mesh.getChildMeshes().forEach(function (c) {
                _this._setAllVisibility(c, value);
            });
        };
        return FadeInOutBehavior;
    }());
    BABYLON.FadeInOutBehavior = FadeInOutBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.fadeInOutBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
     */
    var Gizmo = /** @class */ (function () {
        /**
         * Creates a gizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         */
        function Gizmo(
        /** The utility layer the gizmo will be added to */
        gizmoLayer) {
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            var _this = this;
            this.gizmoLayer = gizmoLayer;
            /**
             * Ratio for the scale of the gizmo (Default: 1)
             */
            this.scaleRatio = 1;
            this._tmpMatrix = new BABYLON.Matrix();
            /**
             * If a custom mesh has been set (Default: false)
             */
            this._customMeshSet = false;
            /**
             * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
             */
            this.updateGizmoRotationToMatchAttachedMesh = true;
            /**
             * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
             */
            this.updateGizmoPositionToMatchAttachedMesh = true;
            /**
             * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
             */
            this._updateScale = true;
            this._interactionsEnabled = true;
            this._tempVector = new BABYLON.Vector3();
            this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
            this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
                _this._update();
            });
            this.attachedMesh = null;
        }
        Object.defineProperty(Gizmo.prototype, "attachedMesh", {
            /**
             * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
             * * When set, interactions will be enabled
             */
            get: function () {
                return this._attachedMesh;
            },
            set: function (value) {
                this._attachedMesh = value;
                this._rootMesh.setEnabled(value ? true : false);
                this._attachedMeshChanged(value);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes and replaces the current meshes in the gizmo with the specified mesh
         * @param mesh The mesh to replace the default mesh of the gizmo
         */
        Gizmo.prototype.setCustomMesh = function (mesh) {
            if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
                throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
            }
            this._rootMesh.getChildMeshes().forEach(function (c) {
                c.dispose();
            });
            mesh.parent = this._rootMesh;
            this._customMeshSet = true;
        };
        Gizmo.prototype._attachedMeshChanged = function (value) {
        };
        /**
         * @hidden
         * Updates the gizmo to match the attached mesh's position/rotation
         */
        Gizmo.prototype._update = function () {
            if (this.attachedMesh) {
                if (this.updateGizmoRotationToMatchAttachedMesh) {
                    if (!this._rootMesh.rotationQuaternion) {
                        this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
                    }
                    // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
                    this._tempVector.copyFrom(this.attachedMesh.scaling);
                    if (this.attachedMesh.scaling.x < 0) {
                        this.attachedMesh.scaling.x *= -1;
                    }
                    if (this.attachedMesh.scaling.y < 0) {
                        this.attachedMesh.scaling.y *= -1;
                    }
                    if (this.attachedMesh.scaling.z < 0) {
                        this.attachedMesh.scaling.z *= -1;
                    }
                    this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
                    this.attachedMesh.scaling.copyFrom(this._tempVector);
                    this.attachedMesh.computeWorldMatrix();
                    BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
                }
                else if (this._rootMesh.rotationQuaternion) {
                    this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
                }
                if (this.updateGizmoPositionToMatchAttachedMesh) {
                    this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
                }
                if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
                    var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
                    if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
                        cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
                    }
                    this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
                    var dist = this._tempVector.length() * this.scaleRatio;
                    this._rootMesh.scaling.set(dist, dist, dist);
                }
            }
        };
        /**
         * Disposes of the gizmo
         */
        Gizmo.prototype.dispose = function () {
            this._rootMesh.dispose();
            if (this._beforeRenderObserver) {
                this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
            }
        };
        return Gizmo;
    }());
    BABYLON.Gizmo = Gizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Single axis drag gizmo
     */
    var AxisDragGizmo = /** @class */ (function (_super) {
        __extends(AxisDragGizmo, _super);
        /**
         * Creates an AxisDragGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         * @param dragAxis The axis which the gizmo will be able to drag on
         * @param color The color of the gizmo
         */
        function AxisDragGizmo(dragAxis, color, gizmoLayer) {
            if (color === void 0) { color = BABYLON.Color3.Gray(); }
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            var _this = _super.call(this, gizmoLayer) || this;
            _this._pointerObserver = null;
            /**
             * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
             */
            _this.snapDistance = 0;
            /**
             * Event that fires each time the gizmo snaps to a new location.
             * * snapDistance is the the change in distance
             */
            _this.onSnapObservable = new BABYLON.Observable();
            // Create Material
            var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            coloredMaterial.disableLighting = true;
            coloredMaterial.emissiveColor = color;
            var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            hoverMaterial.disableLighting = true;
            hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
            // Build mesh on root node
            var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
            var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
            var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
            arrowTail.color = coloredMaterial.emissiveColor;
            arrow.addChild(arrowMesh);
            arrow.addChild(arrowTail);
            // Position arrow pointing in its drag axis
            arrowMesh.scaling.scaleInPlace(0.05);
            arrowMesh.material = coloredMaterial;
            arrowMesh.rotation.x = Math.PI / 2;
            arrowMesh.position.z += 0.3;
            arrowTail.scaling.scaleInPlace(0.26);
            arrowTail.rotation.x = Math.PI / 2;
            arrowTail.material = coloredMaterial;
            arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
            arrow.scaling.scaleInPlace(1 / 3);
            _this._rootMesh.addChild(arrow);
            var currentSnapDragDistance = 0;
            var tmpVector = new BABYLON.Vector3();
            var tmpSnapEvent = { snapDistance: 0 };
            // Add drag behavior to handle events when the gizmo is dragged
            _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
            _this.dragBehavior.moveAttached = false;
            _this._rootMesh.addBehavior(_this.dragBehavior);
            var localDelta = new BABYLON.Vector3();
            var tmpMatrix = new BABYLON.Matrix();
            _this.dragBehavior.onDragObservable.add(function (event) {
                if (_this.attachedMesh) {
                    // Convert delta to local translation if it has a parent
                    if (_this.attachedMesh.parent) {
                        _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
                        tmpMatrix.setTranslationFromFloats(0, 0, 0);
                        BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
                    }
                    else {
                        localDelta.copyFrom(event.delta);
                    }
                    // Snapping logic
                    if (_this.snapDistance == 0) {
                        _this.attachedMesh.position.addInPlace(localDelta);
                    }
                    else {
                        currentSnapDragDistance += event.dragDistance;
                        if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
                            var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
                            currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
                            localDelta.normalizeToRef(tmpVector);
                            tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
                            _this.attachedMesh.position.addInPlace(tmpVector);
                            tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
                            _this.onSnapObservable.notifyObservers(tmpSnapEvent);
                        }
                    }
                }
            });
            _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
                if (_this._customMeshSet) {
                    return;
                }
                var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
                var material = isHovered ? hoverMaterial : coloredMaterial;
                _this._rootMesh.getChildMeshes().forEach(function (m) {
                    m.material = material;
                    if (m.color) {
                        m.color = material.emissiveColor;
                    }
                });
            });
            return _this;
        }
        AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
            if (this.dragBehavior) {
                this.dragBehavior.enabled = value ? true : false;
            }
        };
        /**
         * Disposes of the gizmo
         */
        AxisDragGizmo.prototype.dispose = function () {
            this.onSnapObservable.clear();
            this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
            this.dragBehavior.detach();
            _super.prototype.dispose.call(this);
        };
        return AxisDragGizmo;
    }(BABYLON.Gizmo));
    BABYLON.AxisDragGizmo = AxisDragGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.axisDragGizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Single axis scale gizmo
     */
    var AxisScaleGizmo = /** @class */ (function (_super) {
        __extends(AxisScaleGizmo, _super);
        /**
         * Creates an AxisScaleGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         * @param dragAxis The axis which the gizmo will be able to scale on
         * @param color The color of the gizmo
         */
        function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
            if (color === void 0) { color = BABYLON.Color3.Gray(); }
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            var _this = _super.call(this, gizmoLayer) || this;
            _this._pointerObserver = null;
            /**
             * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
             */
            _this.snapDistance = 0;
            /**
             * Event that fires each time the gizmo snaps to a new location.
             * * snapDistance is the the change in distance
             */
            _this.onSnapObservable = new BABYLON.Observable();
            /**
             * If the scaling operation should be done on all axis (default: false)
             */
            _this.uniformScaling = false;
            // Create Material
            _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            _this._coloredMaterial.disableLighting = true;
            _this._coloredMaterial.emissiveColor = color;
            var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            hoverMaterial.disableLighting = true;
            hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
            // Build mesh on root node
            var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
            var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
            var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
            arrowTail.color = _this._coloredMaterial.emissiveColor;
            arrow.addChild(arrowMesh);
            arrow.addChild(arrowTail);
            // Position arrow pointing in its drag axis
            arrowMesh.scaling.scaleInPlace(0.1);
            arrowMesh.material = _this._coloredMaterial;
            arrowMesh.rotation.x = Math.PI / 2;
            arrowMesh.position.z += 0.3;
            arrowTail.scaling.scaleInPlace(0.26);
            arrowTail.rotation.x = Math.PI / 2;
            arrowTail.material = _this._coloredMaterial;
            arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
            _this._rootMesh.addChild(arrow);
            arrow.scaling.scaleInPlace(1 / 3);
            // Add drag behavior to handle events when the gizmo is dragged
            _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
            _this.dragBehavior.moveAttached = false;
            _this._rootMesh.addBehavior(_this.dragBehavior);
            var currentSnapDragDistance = 0;
            var tmpVector = new BABYLON.Vector3();
            var tmpSnapEvent = { snapDistance: 0 };
            _this.dragBehavior.onDragObservable.add(function (event) {
                if (_this.attachedMesh) {
                    // Snapping logic
                    var snapped = false;
                    var dragSteps = 0;
                    if (_this.uniformScaling) {
                        _this.attachedMesh.scaling.normalizeToRef(tmpVector);
                        if (tmpVector.y < 0) {
                            tmpVector.scaleInPlace(-1);
                        }
                    }
                    else {
                        tmpVector.copyFrom(dragAxis);
                    }
                    if (_this.snapDistance == 0) {
                        tmpVector.scaleToRef(event.dragDistance, tmpVector);
                    }
                    else {
                        currentSnapDragDistance += event.dragDistance;
                        if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
                            dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
                            currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
                            tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
                            snapped = true;
                        }
                        else {
                            tmpVector.scaleInPlace(0);
                        }
                    }
                    _this.attachedMesh.scaling.addInPlace(tmpVector);
                    if (snapped) {
                        tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
                        _this.onSnapObservable.notifyObservers(tmpSnapEvent);
                    }
                }
            });
            _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
                if (_this._customMeshSet) {
                    return;
                }
                var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
                var material = isHovered ? hoverMaterial : _this._coloredMaterial;
                _this._rootMesh.getChildMeshes().forEach(function (m) {
                    m.material = material;
                    if (m.color) {
                        m.color = material.emissiveColor;
                    }
                });
            });
            return _this;
        }
        AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
            if (this.dragBehavior) {
                this.dragBehavior.enabled = value ? true : false;
            }
        };
        /**
         * Disposes of the gizmo
         */
        AxisScaleGizmo.prototype.dispose = function () {
            this.onSnapObservable.clear();
            this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
            this.dragBehavior.detach();
            _super.prototype.dispose.call(this);
        };
        /**
         * Disposes and replaces the current meshes in the gizmo with the specified mesh
         * @param mesh The mesh to replace the default mesh of the gizmo
         * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
         */
        AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
            var _this = this;
            if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
            _super.prototype.setCustomMesh.call(this, mesh);
            if (useGizmoMaterial) {
                this._rootMesh.getChildMeshes().forEach(function (m) {
                    m.material = _this._coloredMaterial;
                    if (m.color) {
                        m.color = _this._coloredMaterial.emissiveColor;
                    }
                });
                this._customMeshSet = false;
            }
        };
        return AxisScaleGizmo;
    }(BABYLON.Gizmo));
    BABYLON.AxisScaleGizmo = AxisScaleGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.axisScaleGizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Single plane rotation gizmo
     */
    var PlaneRotationGizmo = /** @class */ (function (_super) {
        __extends(PlaneRotationGizmo, _super);
        /**
         * Creates a PlaneRotationGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
         * @param color The color of the gizmo
         * @param tessellation Amount of tessellation to be used when creating rotation circles
         */
        function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
            if (color === void 0) { color = BABYLON.Color3.Gray(); }
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            if (tessellation === void 0) { tessellation = 32; }
            var _this = _super.call(this, gizmoLayer) || this;
            _this._pointerObserver = null;
            /**
             * Rotation distance in radians that the gizmo will snap to (Default: 0)
             */
            _this.snapDistance = 0;
            /**
             * Event that fires each time the gizmo snaps to a new location.
             * * snapDistance is the the change in distance
             */
            _this.onSnapObservable = new BABYLON.Observable();
            // Create Material
            var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            coloredMaterial.disableLighting = true;
            coloredMaterial.emissiveColor = color;
            var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            hoverMaterial.disableLighting = true;
            hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
            // Build mesh on root node
            var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
            // Create circle out of lines
            var radius = 0.8;
            var points = new Array();
            for (var i = 0; i < tessellation; i++) {
                var radian = (2 * Math.PI) * (i / (tessellation - 1));
                points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
            }
            var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
            rotationMesh.color = coloredMaterial.emissiveColor;
            // Position arrow pointing in its drag axis
            rotationMesh.scaling.scaleInPlace(0.26);
            rotationMesh.material = coloredMaterial;
            rotationMesh.rotation.x = Math.PI / 2;
            parentMesh.addChild(rotationMesh);
            parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
            _this._rootMesh.addChild(parentMesh);
            parentMesh.scaling.scaleInPlace(1 / 3);
            // Add drag behavior to handle events when the gizmo is dragged
            _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
            _this.dragBehavior.moveAttached = false;
            _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
            _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
            _this._rootMesh.addBehavior(_this.dragBehavior);
            var lastDragPosition = new BABYLON.Vector3();
            _this.dragBehavior.onDragStartObservable.add(function (e) {
                if (_this.attachedMesh) {
                    lastDragPosition.copyFrom(e.dragPlanePoint);
                }
            });
            var rotationMatrix = new BABYLON.Matrix();
            var planeNormalTowardsCamera = new BABYLON.Vector3();
            var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
            var tmpSnapEvent = { snapDistance: 0 };
            var currentSnapDragDistance = 0;
            var tmpMatrix = new BABYLON.Matrix();
            var tmpVector = new BABYLON.Vector3();
            var amountToRotate = new BABYLON.Quaternion();
            _this.dragBehavior.onDragObservable.add(function (event) {
                if (_this.attachedMesh) {
                    if (!_this.attachedMesh.rotationQuaternion) {
                        _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
                    }
                    // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
                    var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
                    var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
                    var cross = BABYLON.Vector3.Cross(newVector, originalVector);
                    var dot = BABYLON.Vector3.Dot(newVector, originalVector);
                    var angle = Math.atan2(cross.length(), dot);
                    planeNormalTowardsCamera.copyFrom(planeNormal);
                    localPlaneNormalTowardsCamera.copyFrom(planeNormal);
                    if (_this.updateGizmoRotationToMatchAttachedMesh) {
                        _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
                        localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
                    }
                    // Flip up vector depending on which side the camera is on
                    if (gizmoLayer.utilityLayerScene.activeCamera) {
                        var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
                        if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
                            planeNormalTowardsCamera.scaleInPlace(-1);
                            localPlaneNormalTowardsCamera.scaleInPlace(-1);
                        }
                    }
                    var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
                    if (halfCircleSide) {
                        angle = -angle;
                    }
                    // Snapping logic
                    var snapped = false;
                    if (_this.snapDistance != 0) {
                        currentSnapDragDistance += angle;
                        if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
                            var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
                            currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
                            angle = _this.snapDistance * dragSteps;
                            snapped = true;
                        }
                        else {
                            angle = 0;
                        }
                    }
                    // If the mesh has a parent, convert needed world rotation to local rotation
                    tmpMatrix.reset();
                    if (_this.attachedMesh.parent) {
                        _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
                        tmpMatrix.getRotationMatrixToRef(tmpMatrix);
                        BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
                    }
                    // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
                    var quaternionCoefficient = Math.sin(angle / 2);
                    amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
                    // If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
                    if (tmpMatrix.determinant() > 0) {
                        amountToRotate.toEulerAnglesToRef(tmpVector);
                        BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
                    }
                    if (_this.updateGizmoRotationToMatchAttachedMesh) {
                        // Rotate selected mesh quaternion over fixed axis
                        _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
                    }
                    else {
                        // Rotate selected mesh quaternion over rotated axis
                        amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
                    }
                    lastDragPosition.copyFrom(event.dragPlanePoint);
                    if (snapped) {
                        tmpSnapEvent.snapDistance = angle;
                        _this.onSnapObservable.notifyObservers(tmpSnapEvent);
                    }
                }
            });
            _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
                if (_this._customMeshSet) {
                    return;
                }
                var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
                var material = isHovered ? hoverMaterial : coloredMaterial;
                _this._rootMesh.getChildMeshes().forEach(function (m) {
                    m.material = material;
                    if (m.color) {
                        m.color = material.emissiveColor;
                    }
                });
            });
            return _this;
        }
        PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
            if (this.dragBehavior) {
                this.dragBehavior.enabled = value ? true : false;
            }
        };
        /**
         * Disposes of the gizmo
         */
        PlaneRotationGizmo.prototype.dispose = function () {
            this.onSnapObservable.clear();
            this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
            this.dragBehavior.detach();
            _super.prototype.dispose.call(this);
        };
        return PlaneRotationGizmo;
    }(BABYLON.Gizmo));
    BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.planeRotationGizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Gizmo that enables dragging a mesh along 3 axis
     */
    var PositionGizmo = /** @class */ (function (_super) {
        __extends(PositionGizmo, _super);
        /**
         * Creates a PositionGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         */
        function PositionGizmo(gizmoLayer) {
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            var _this = _super.call(this, gizmoLayer) || this;
            /** Fires an event when any of it's sub gizmos are dragged */
            _this.onDragStartObservable = new BABYLON.Observable();
            /** Fires an event when any of it's sub gizmos are released from dragging */
            _this.onDragEndObservable = new BABYLON.Observable();
            _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
            _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
            _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
            // Relay drag events
            [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
                gizmo.dragBehavior.onDragStartObservable.add(function () {
                    _this.onDragStartObservable.notifyObservers({});
                });
                gizmo.dragBehavior.onDragEndObservable.add(function () {
                    _this.onDragEndObservable.notifyObservers({});
                });
            });
            _this.attachedMesh = null;
            return _this;
        }
        Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
            set: function (mesh) {
                if (this.xGizmo) {
                    this.xGizmo.attachedMesh = mesh;
                    this.yGizmo.attachedMesh = mesh;
                    this.zGizmo.attachedMesh = mesh;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
            get: function () {
                return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
            },
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                    this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                    this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
            get: function () {
                return this.xGizmo.snapDistance;
            },
            /**
             * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
             */
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.snapDistance = value;
                    this.yGizmo.snapDistance = value;
                    this.zGizmo.snapDistance = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
            get: function () {
                return this.xGizmo.scaleRatio;
            },
            /**
             * Ratio for the scale of the gizmo (Default: 1)
             */
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.scaleRatio = value;
                    this.yGizmo.scaleRatio = value;
                    this.zGizmo.scaleRatio = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes of the gizmo
         */
        PositionGizmo.prototype.dispose = function () {
            this.xGizmo.dispose();
            this.yGizmo.dispose();
            this.zGizmo.dispose();
            this.onDragStartObservable.clear();
            this.onDragEndObservable.clear();
        };
        /**
         * CustomMeshes are not supported by this gizmo
         * @param mesh The mesh to replace the default mesh of the gizmo
         */
        PositionGizmo.prototype.setCustomMesh = function (mesh) {
            BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
        };
        return PositionGizmo;
    }(BABYLON.Gizmo));
    BABYLON.PositionGizmo = PositionGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.positionGizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Gizmo that enables rotating a mesh along 3 axis
     */
    var RotationGizmo = /** @class */ (function (_super) {
        __extends(RotationGizmo, _super);
        /**
         * Creates a RotationGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         * @param tessellation Amount of tessellation to be used when creating rotation circles
         */
        function RotationGizmo(gizmoLayer, tessellation) {
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            if (tessellation === void 0) { tessellation = 32; }
            var _this = _super.call(this, gizmoLayer) || this;
            /** Fires an event when any of it's sub gizmos are dragged */
            _this.onDragStartObservable = new BABYLON.Observable();
            /** Fires an event when any of it's sub gizmos are released from dragging */
            _this.onDragEndObservable = new BABYLON.Observable();
            _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
            _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
            _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
            // Relay drag events
            [_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
                gizmo.dragBehavior.onDragStartObservable.add(function () {
                    _this.onDragStartObservable.notifyObservers({});
                });
                gizmo.dragBehavior.onDragEndObservable.add(function () {
                    _this.onDragEndObservable.notifyObservers({});
                });
            });
            _this.attachedMesh = null;
            return _this;
        }
        Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
            set: function (mesh) {
                if (this.xGizmo) {
                    this.xGizmo.attachedMesh = mesh;
                    this.yGizmo.attachedMesh = mesh;
                    this.zGizmo.attachedMesh = mesh;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
            get: function () {
                return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
            },
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                    this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                    this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
            get: function () {
                return this.xGizmo.snapDistance;
            },
            /**
             * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
             */
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.snapDistance = value;
                    this.yGizmo.snapDistance = value;
                    this.zGizmo.snapDistance = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
            get: function () {
                return this.xGizmo.scaleRatio;
            },
            /**
             * Ratio for the scale of the gizmo (Default: 1)
             */
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.scaleRatio = value;
                    this.yGizmo.scaleRatio = value;
                    this.zGizmo.scaleRatio = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes of the gizmo
         */
        RotationGizmo.prototype.dispose = function () {
            this.xGizmo.dispose();
            this.yGizmo.dispose();
            this.zGizmo.dispose();
            this.onDragStartObservable.clear();
            this.onDragEndObservable.clear();
        };
        /**
         * CustomMeshes are not supported by this gizmo
         * @param mesh The mesh to replace the default mesh of the gizmo
         */
        RotationGizmo.prototype.setCustomMesh = function (mesh) {
            BABYLON.Tools.Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
        };
        return RotationGizmo;
    }(BABYLON.Gizmo));
    BABYLON.RotationGizmo = RotationGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.rotationGizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Gizmo that enables scaling a mesh along 3 axis
     */
    var ScaleGizmo = /** @class */ (function (_super) {
        __extends(ScaleGizmo, _super);
        /**
         * Creates a ScaleGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         */
        function ScaleGizmo(gizmoLayer) {
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
            var _this = _super.call(this, gizmoLayer) || this;
            /** Fires an event when any of it's sub gizmos are dragged */
            _this.onDragStartObservable = new BABYLON.Observable();
            /** Fires an event when any of it's sub gizmos are released from dragging */
            _this.onDragEndObservable = new BABYLON.Observable();
            _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
            _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
            _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
            // Create uniform scale gizmo
            _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
            _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
            _this.uniformScaleGizmo.uniformScaling = true;
            var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
            uniformScalingMesh.scaling.scaleInPlace(0.02);
            uniformScalingMesh.visibility = 0;
            var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
            octahedron.scaling.scaleInPlace(0.007);
            uniformScalingMesh.addChild(octahedron);
            _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
            // Relay drag events
            [_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
                gizmo.dragBehavior.onDragStartObservable.add(function () {
                    _this.onDragStartObservable.notifyObservers({});
                });
                gizmo.dragBehavior.onDragEndObservable.add(function () {
                    _this.onDragEndObservable.notifyObservers({});
                });
            });
            _this.attachedMesh = null;
            return _this;
        }
        Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
            set: function (mesh) {
                if (this.xGizmo) {
                    this.xGizmo.attachedMesh = mesh;
                    this.yGizmo.attachedMesh = mesh;
                    this.zGizmo.attachedMesh = mesh;
                    this.uniformScaleGizmo.attachedMesh = mesh;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
            get: function () {
                return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
            },
            set: function (value) {
                if (!value) {
                    BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
                }
                if (this.xGizmo) {
                    this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                    this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                    this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
            get: function () {
                return this.xGizmo.snapDistance;
            },
            /**
             * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
             */
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.snapDistance = value;
                    this.yGizmo.snapDistance = value;
                    this.zGizmo.snapDistance = value;
                    this.uniformScaleGizmo.snapDistance = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
            get: function () {
                return this.xGizmo.scaleRatio;
            },
            /**
             * Ratio for the scale of the gizmo (Default: 1)
             */
            set: function (value) {
                if (this.xGizmo) {
                    this.xGizmo.scaleRatio = value;
                    this.yGizmo.scaleRatio = value;
                    this.zGizmo.scaleRatio = value;
                    this.uniformScaleGizmo.scaleRatio = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes of the gizmo
         */
        ScaleGizmo.prototype.dispose = function () {
            this.xGizmo.dispose();
            this.yGizmo.dispose();
            this.zGizmo.dispose();
            this.uniformScaleGizmo.dispose();
            this.onDragStartObservable.clear();
            this.onDragEndObservable.clear();
        };
        return ScaleGizmo;
    }(BABYLON.Gizmo));
    BABYLON.ScaleGizmo = ScaleGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.scaleGizmo.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Bounding box gizmo
     */
    var BoundingBoxGizmo = /** @class */ (function (_super) {
        __extends(BoundingBoxGizmo, _super);
        /**
         * Creates an BoundingBoxGizmo
         * @param gizmoLayer The utility layer the gizmo will be added to
         * @param color The color of the gizmo
         */
        function BoundingBoxGizmo(color, gizmoLayer) {
            if (color === void 0) { color = BABYLON.Color3.Gray(); }
            if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
            var _this = _super.call(this, gizmoLayer) || this;
            _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
            _this._renderObserver = null;
            _this._pointerObserver = null;
            _this._scaleDragSpeed = 0.2;
            _this._tmpQuaternion = new BABYLON.Quaternion();
            _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
            _this._tmpRotationMatrix = new BABYLON.Matrix();
            /**
             * If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
             */
            _this.ignoreChildren = false;
            /**
             * Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
             */
            _this.includeChildPredicate = null;
            /**
             * The size of the rotation spheres attached to the bounding box (Default: 0.1)
             */
            _this.rotationSphereSize = 0.1;
            /**
             * The size of the scale boxes attached to the bounding box (Default: 0.1)
             */
            _this.scaleBoxSize = 0.1;
            /**
             * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
             */
            _this.fixedDragMeshScreenSize = false;
            /**
             * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
             */
            _this.fixedDragMeshScreenSizeDistanceFactor = 10;
            /**
             * Fired when a rotation sphere or scale box is dragged
             */
            _this.onDragStartObservable = new BABYLON.Observable();
            /**
             * Fired when a scale box is dragged
             */
            _this.onScaleBoxDragObservable = new BABYLON.Observable();
            /**
              * Fired when a scale box drag is ended
             */
            _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
            /**
             * Fired when a rotation sphere is dragged
             */
            _this.onRotationSphereDragObservable = new BABYLON.Observable();
            /**
             * Fired when a rotation sphere drag is ended
             */
            _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
            /**
             * Relative bounding box pivot used when scaling the attached mesh. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
             */
            _this.scalePivot = null;
            _this._existingMeshScale = new BABYLON.Vector3();
            // Do not update the gizmo's scale so it has a fixed size to the object its attached to
            _this._updateScale = false;
            _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
            // Create Materials
            var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            coloredMaterial.disableLighting = true;
            coloredMaterial.emissiveColor = color;
            var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
            hoverColoredMaterial.disableLighting = true;
            hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
            // Build bounding box out of lines
            _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
            _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
            var lines = [];
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
            lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
            lines.forEach(function (l) {
                l.color = color;
                l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
                l.isPickable = false;
                _this._lineBoundingBox.addChild(l);
            });
            _this._rootMesh.addChild(_this._lineBoundingBox);
            // Create rotation spheres
            _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
            _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
            var _loop_1 = function (i_1) {
                var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
                sphere.rotationQuaternion = new BABYLON.Quaternion();
                sphere.material = coloredMaterial;
                // Drag behavior
                _dragBehavior = new BABYLON.PointerDragBehavior({});
                _dragBehavior.moveAttached = false;
                _dragBehavior.updateDragPlane = false;
                sphere.addBehavior(_dragBehavior);
                var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
                var totalTurnAmountOfDrag = 0;
                _dragBehavior.onDragStartObservable.add(function (event) {
                    startingTurnDirection.copyFrom(sphere.forward);
                    totalTurnAmountOfDrag = 0;
                });
                _dragBehavior.onDragObservable.add(function (event) {
                    _this.onRotationSphereDragObservable.notifyObservers({});
                    if (_this.attachedMesh) {
                        BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
                        var worldDragDirection = startingTurnDirection;
                        // Project the world right on to the drag plane
                        var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
                        var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
                        // project drag delta on to the resulting drag axis and rotate based on that
                        var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
                        // Make rotation relative to size of mesh.
                        projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
                        // Rotate based on axis
                        if (!_this.attachedMesh.rotationQuaternion) {
                            _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
                        }
                        if (!_this._anchorMesh.rotationQuaternion) {
                            _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
                        }
                        // Do not allow the object to turn more than a full circle
                        totalTurnAmountOfDrag += projectDist;
                        if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
                            if (i_1 >= 8) {
                                BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
                            }
                            else if (i_1 >= 4) {
                                BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
                            }
                            else {
                                BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
                            }
                            // Rotate around center of bounding box
                            _this._anchorMesh.addChild(_this.attachedMesh);
                            _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
                            _this._anchorMesh.removeChild(_this.attachedMesh);
                        }
                        _this.updateBoundingBox();
                        BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
                    }
                });
                // Selection/deselection
                _dragBehavior.onDragStartObservable.add(function () {
                    _this.onDragStartObservable.notifyObservers({});
                    _this._selectNode(sphere);
                });
                _dragBehavior.onDragEndObservable.add(function () {
                    _this.onRotationSphereDragEndObservable.notifyObservers({});
                    _this._selectNode(null);
                });
                this_1._rotateSpheresParent.addChild(sphere);
            };
            var this_1 = this, _dragBehavior;
            for (var i_1 = 0; i_1 < 12; i_1++) {
                _loop_1(i_1);
            }
            _this._rootMesh.addChild(_this._rotateSpheresParent);
            // Create scale cubes
            _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
            _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
            for (var i = 0; i < 2; i++) {
                for (var j = 0; j < 2; j++) {
                    var _loop_2 = function () {
                        var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
                        box.material = coloredMaterial;
                        // Dragging logic
                        var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
                        _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
                        _dragBehavior.moveAttached = false;
                        box.addBehavior(_dragBehavior);
                        _dragBehavior.onDragObservable.add(function (event) {
                            _this.onScaleBoxDragObservable.notifyObservers({});
                            if (_this.attachedMesh) {
                                BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
                                var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
                                var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
                                deltaScale.scaleInPlace(_this._scaleDragSpeed);
                                _this.updateBoundingBox();
                                if (_this.scalePivot) {
                                    _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
                                    // Move anchor to desired pivot point (Bottom left corner + dimension/2)
                                    _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
                                    BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
                                    _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
                                    _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
                                    BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
                                    _this._anchorMesh.position.addInPlace(_this._tmpVector);
                                }
                                else {
                                    // Scale from the position of the opposite corner
                                    box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
                                    _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
                                }
                                _this._anchorMesh.addChild(_this.attachedMesh);
                                _this._anchorMesh.scaling.addInPlace(deltaScale);
                                if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
                                    _this._anchorMesh.scaling.subtractInPlace(deltaScale);
                                }
                                _this._anchorMesh.removeChild(_this.attachedMesh);
                                BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
                            }
                        });
                        // Selection/deselection
                        _dragBehavior.onDragStartObservable.add(function () {
                            _this.onDragStartObservable.notifyObservers({});
                            _this._selectNode(box);
                        });
                        _dragBehavior.onDragEndObservable.add(function () {
                            _this.onScaleBoxDragEndObservable.notifyObservers({});
                            _this._selectNode(null);
                        });
                        this_2._scaleBoxesParent.addChild(box);
                    };
                    var this_2 = this, _dragBehavior;
                    for (var k = 0; k < 2; k++) {
                        _loop_2();
                    }
                }
            }
            _this._rootMesh.addChild(_this._scaleBoxesParent);
            // Hover color change
            var pointerIds = new Array();
            _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
                if (!pointerIds[pointerInfo.event.pointerId]) {
                    _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
                        if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
                            pointerIds[pointerInfo.event.pointerId] = mesh;
                            mesh.material = hoverColoredMaterial;
                        }
                    });
                }
                else {
                    if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
                        pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
                        delete pointerIds[pointerInfo.event.pointerId];
                    }
                }
            });
            // Update bounding box positions
            _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
                // Only update the bouding box if scaling has changed
                if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
                    _this.updateBoundingBox();
                }
            });
            _this.updateBoundingBox();
            return _this;
        }
        /** @hidden */
        BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
            if (mesh && BoundingBoxGizmo._PivotCached === 0) {
                // Save old pivot and set pivot to 0,0,0
                mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
                if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
                    mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
                    BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
                    BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
                    BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
                    BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
                    mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
                }
            }
            BoundingBoxGizmo._PivotCached++;
        };
        /** @hidden */
        BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
            if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
                mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
                BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
                BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
                BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
                mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
            }
            this._PivotCached--;
        };
        BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
            if (value) {
                // Reset anchor mesh to match attached mesh's scale
                // This is needed to avoid invalid box/sphere position on first drag
                BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
                this._anchorMesh.addChild(value);
                this._anchorMesh.removeChild(value);
                BoundingBoxGizmo._RestorePivotPoint(value);
                this.updateBoundingBox();
            }
        };
        BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
            this._rotateSpheresParent.getChildMeshes()
                .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
                m.isVisible = (!selectedMesh || m == selectedMesh);
            });
        };
        /**
         * Updates the bounding box information for the Gizmo
         */
        BoundingBoxGizmo.prototype.updateBoundingBox = function () {
            if (this.attachedMesh) {
                BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
                this._update();
                // Rotate based on axis
                if (!this.attachedMesh.rotationQuaternion) {
                    this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
                }
                if (!this._anchorMesh.rotationQuaternion) {
                    this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
                }
                this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
                // Store original position and reset mesh to origin before computing the bounding box
                this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
                this._tmpVector.copyFrom(this.attachedMesh.position);
                this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
                this.attachedMesh.position.set(0, 0, 0);
                // Update bounding dimensions/positions
                var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
                boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
                // Update gizmo to match bounding box scaling and rotation
                this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
                this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
                this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
                this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
                this._lineBoundingBox.computeWorldMatrix();
                this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
                // restore position/rotation values
                this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
                this.attachedMesh.position.copyFrom(this._tmpVector);
            }
            // Update rotation sphere locations
            var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
            for (var i = 0; i < 3; i++) {
                for (var j = 0; j < 2; j++) {
                    for (var k = 0; k < 2; k++) {
                        var index = ((i * 4) + (j * 2)) + k;
                        if (i == 0) {
                            rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
                            rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
                            rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
                        }
                        if (i == 1) {
                            rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
                            rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
                            rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
                        }
                        if (i == 2) {
                            rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
                            rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
                            rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
                        }
                        if (this.fixedDragMeshScreenSize) {
                            this._rootMesh.computeWorldMatrix();
                            this._rotateSpheresParent.computeWorldMatrix();
                            rotateSpheres[index].computeWorldMatrix();
                            rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
                            var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
                            rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
                        }
                        else {
                            rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
                        }
                    }
                }
            }
            // Update scale box locations
            var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
            for (var i = 0; i < 2; i++) {
                for (var j = 0; j < 2; j++) {
                    for (var k = 0; k < 2; k++) {
                        var index = ((i * 4) + (j * 2)) + k;
                        if (scaleBoxes[index]) {
                            scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
                            scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
                            if (this.fixedDragMeshScreenSize) {
                                this._rootMesh.computeWorldMatrix();
                                this._scaleBoxesParent.computeWorldMatrix();
                                scaleBoxes[index].computeWorldMatrix();
                                scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
                                var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
                                scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
                            }
                            else {
                                scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
                            }
                        }
                    }
                }
            }
            if (this.attachedMesh) {
                this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
                BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
            }
        };
        /**
         * Enables rotation on the specified axis and disables rotation on the others
         * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
         */
        BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
            this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
                if (i < 4) {
                    m.setEnabled(axis.indexOf("x") != -1);
                }
                else if (i < 8) {
                    m.setEnabled(axis.indexOf("y") != -1);
                }
                else {
                    m.setEnabled(axis.indexOf("z") != -1);
                }
            });
        };
        /**
         * Disposes of the gizmo
         */
        BoundingBoxGizmo.prototype.dispose = function () {
            this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
            this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
            this._lineBoundingBox.dispose();
            this._rotateSpheresParent.dispose();
            this._scaleBoxesParent.dispose();
            _super.prototype.dispose.call(this);
        };
        /**
         * Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
         * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
         * @returns the bounding box mesh with the passed in mesh as a child
         */
        BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
            var makeNotPickable = function (root) {
                root.isPickable = false;
                root.getChildMeshes().forEach(function (c) {
                    makeNotPickable(c);
                });
            };
            makeNotPickable(mesh);
            // Reset position to get boudning box from origin with no rotation
            if (!mesh.rotationQuaternion) {
                mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
            }
            var oldPos = mesh.position.clone();
            var oldRot = mesh.rotationQuaternion.clone();
            mesh.rotationQuaternion.set(0, 0, 0, 1);
            mesh.position.set(0, 0, 0);
            // Update bounding dimensions/positions
            var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
            var boundingMinMax = mesh.getHierarchyBoundingVectors();
            boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
            box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
            // Restore original positions
            mesh.addChild(box);
            mesh.rotationQuaternion.copyFrom(oldRot);
            mesh.position.copyFrom(oldPos);
            // Reverse parenting
            mesh.removeChild(box);
            box.addChild(mesh);
            box.visibility = 0;
            return box;
        };
        /**
         * CustomMeshes are not supported by this gizmo
         * @param mesh The mesh to replace the default mesh of the gizmo
         */
        BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
            BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
        };
        // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
        // store/remove pivot point should only be applied during their outermost calls
        BoundingBoxGizmo._PivotCached = 0;
        BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
        BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
        BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
        return BoundingBoxGizmo;
    }(BABYLON.Gizmo));
    BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.boundingBoxGizmo.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Helps setup gizmo's in the scene to rotate/scale/position meshes
     */
    var GizmoManager = /** @class */ (function () {
        /**
         * Instatiates a gizmo manager
         * @param scene the scene to overlay the gizmos on top of
         */
        function GizmoManager(scene) {
            var _this = this;
            this.scene = scene;
            this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
            this._pointerObserver = null;
            this._attachedMesh = null;
            this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
            /**
             * When bounding box gizmo is enabled, this can be used to track drag/end events
             */
            this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
            /**
             * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
             */
            this.attachableMeshes = null;
            /**
             * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
             */
            this.usePointerToAttachGizmos = true;
            this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
            this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
            this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
            this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
            // Instatiate/dispose gizmos based on pointer actions
            this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
                if (!_this.usePointerToAttachGizmos) {
                    return;
                }
                if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
                    if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
                        var node = pointerInfo.pickInfo.pickedMesh;
                        if (_this.attachableMeshes == null) {
                            // Attach to the most parent node
                            while (node && node.parent != null) {
                                node = node.parent;
                            }
                        }
                        else {
                            // Attach to the parent node that is an attachableMesh
                            var found = false;
                            _this.attachableMeshes.forEach(function (mesh) {
                                if (node && (node == mesh || node.isDescendantOf(mesh))) {
                                    node = mesh;
                                    found = true;
                                }
                            });
                            if (!found) {
                                node = null;
                            }
                        }
                        if (node instanceof BABYLON.AbstractMesh) {
                            if (_this._attachedMesh != node) {
                                _this.attachToMesh(node);
                            }
                        }
                        else {
                            _this.attachToMesh(null);
                        }
                    }
                    else {
                        _this.attachToMesh(null);
                    }
                }
            });
        }
        /**
         * Attaches a set of gizmos to the specified mesh
         * @param mesh The mesh the gizmo's should be attached to
         */
        GizmoManager.prototype.attachToMesh = function (mesh) {
            if (this._attachedMesh) {
                this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
            }
            this._attachedMesh = mesh;
            for (var key in this.gizmos) {
                var gizmo = (this.gizmos[key]);
                if (gizmo && this._gizmosEnabled[key]) {
                    gizmo.attachedMesh = mesh;
                }
            }
            if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
                this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
            }
        };
        Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
            get: function () {
                return this._gizmosEnabled.positionGizmo;
            },
            /**
             * If the position gizmo is enabled
             */
            set: function (value) {
                if (value) {
                    if (!this.gizmos.positionGizmo) {
                        this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
                    }
                    this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
                }
                else if (this.gizmos.positionGizmo) {
                    this.gizmos.positionGizmo.attachedMesh = null;
                }
                this._gizmosEnabled.positionGizmo = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
            get: function () {
                return this._gizmosEnabled.rotationGizmo;
            },
            /**
             * If the rotation gizmo is enabled
             */
            set: function (value) {
                if (value) {
                    if (!this.gizmos.rotationGizmo) {
                        this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
                    }
                    this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
                }
                else if (this.gizmos.rotationGizmo) {
                    this.gizmos.rotationGizmo.attachedMesh = null;
                }
                this._gizmosEnabled.rotationGizmo = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
            get: function () {
                return this._gizmosEnabled.scaleGizmo;
            },
            /**
             * If the scale gizmo is enabled
             */
            set: function (value) {
                if (value) {
                    this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
                    this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
                }
                else if (this.gizmos.scaleGizmo) {
                    this.gizmos.scaleGizmo.attachedMesh = null;
                }
                this._gizmosEnabled.scaleGizmo = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
            get: function () {
                return this._gizmosEnabled.boundingBoxGizmo;
            },
            /**
             * If the boundingBox gizmo is enabled
             */
            set: function (value) {
                if (value) {
                    this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
                    this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
                    if (this._attachedMesh) {
                        this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
                        this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
                    }
                }
                else if (this.gizmos.boundingBoxGizmo) {
                    this.gizmos.boundingBoxGizmo.attachedMesh = null;
                }
                this._gizmosEnabled.boundingBoxGizmo = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Disposes of the gizmo manager
         */
        GizmoManager.prototype.dispose = function () {
            this.scene.onPointerObservable.remove(this._pointerObserver);
            for (var key in this.gizmos) {
                var gizmo = (this.gizmos[key]);
                if (gizmo) {
                    gizmo.dispose();
                }
            }
            this._defaultKeepDepthUtilityLayer.dispose();
            this._defaultUtilityLayer.dispose();
            this.boundingBoxDragBehavior.detach();
        };
        return GizmoManager;
    }());
    BABYLON.GizmoManager = GizmoManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.gizmoManager.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Defines a target to use with MorphTargetManager
     * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
     */
    var MorphTarget = /** @class */ (function () {
        /**
         * Creates a new MorphTarget
         * @param name defines the name of the target
         * @param influence defines the influence to use
         */
        function MorphTarget(
        /** defines the name of the target */
        name, influence, scene) {
            if (influence === void 0) { influence = 0; }
            if (scene === void 0) { scene = null; }
            this.name = name;
            /**
             * Gets or sets the list of animations
             */
            this.animations = new Array();
            this._positions = null;
            this._normals = null;
            this._tangents = null;
            /**
             * Observable raised when the influence changes
             */
            this.onInfluenceChanged = new BABYLON.Observable();
            /** @hidden */
            this._onDataLayoutChanged = new BABYLON.Observable();
            this._animationPropertiesOverride = null;
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            this.influence = influence;
        }
        Object.defineProperty(MorphTarget.prototype, "influence", {
            /**
             * Gets or sets the influence of this target (ie. its weight in the overall morphing)
             */
            get: function () {
                return this._influence;
            },
            set: function (influence) {
                if (this._influence === influence) {
                    return;
                }
                var previous = this._influence;
                this._influence = influence;
                if (this.onInfluenceChanged.hasObservers) {
                    this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
            /**
             * Gets or sets the animation properties override
             */
            get: function () {
                if (!this._animationPropertiesOverride && this._scene) {
                    return this._scene.animationPropertiesOverride;
                }
                return this._animationPropertiesOverride;
            },
            set: function (value) {
                this._animationPropertiesOverride = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTarget.prototype, "hasPositions", {
            /**
             * Gets a boolean defining if the target contains position data
             */
            get: function () {
                return !!this._positions;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTarget.prototype, "hasNormals", {
            /**
             * Gets a boolean defining if the target contains normal data
             */
            get: function () {
                return !!this._normals;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTarget.prototype, "hasTangents", {
            /**
             * Gets a boolean defining if the target contains tangent data
             */
            get: function () {
                return !!this._tangents;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Affects position data to this target
         * @param data defines the position data to use
         */
        MorphTarget.prototype.setPositions = function (data) {
            var hadPositions = this.hasPositions;
            this._positions = data;
            if (hadPositions !== this.hasPositions) {
                this._onDataLayoutChanged.notifyObservers(undefined);
            }
        };
        /**
         * Gets the position data stored in this target
         * @returns a FloatArray containing the position data (or null if not present)
         */
        MorphTarget.prototype.getPositions = function () {
            return this._positions;
        };
        /**
         * Affects normal data to this target
         * @param data defines the normal data to use
         */
        MorphTarget.prototype.setNormals = function (data) {
            var hadNormals = this.hasNormals;
            this._normals = data;
            if (hadNormals !== this.hasNormals) {
                this._onDataLayoutChanged.notifyObservers(undefined);
            }
        };
        /**
         * Gets the normal data stored in this target
         * @returns a FloatArray containing the normal data (or null if not present)
         */
        MorphTarget.prototype.getNormals = function () {
            return this._normals;
        };
        /**
         * Affects tangent data to this target
         * @param data defines the tangent data to use
         */
        MorphTarget.prototype.setTangents = function (data) {
            var hadTangents = this.hasTangents;
            this._tangents = data;
            if (hadTangents !== this.hasTangents) {
                this._onDataLayoutChanged.notifyObservers(undefined);
            }
        };
        /**
         * Gets the tangent data stored in this target
         * @returns a FloatArray containing the tangent data (or null if not present)
         */
        MorphTarget.prototype.getTangents = function () {
            return this._tangents;
        };
        /**
         * Serializes the current target into a Serialization object
         * @returns the serialized object
         */
        MorphTarget.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.name = this.name;
            serializationObject.influence = this.influence;
            serializationObject.positions = Array.prototype.slice.call(this.getPositions());
            if (this.hasNormals) {
                serializationObject.normals = Array.prototype.slice.call(this.getNormals());
            }
            if (this.hasTangents) {
                serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
            return serializationObject;
        };
        // Statics
        /**
         * Creates a new target from serialized data
         * @param serializationObject defines the serialized data to use
         * @returns a new MorphTarget
         */
        MorphTarget.Parse = function (serializationObject) {
            var result = new MorphTarget(serializationObject.name, serializationObject.influence);
            result.setPositions(serializationObject.positions);
            if (serializationObject.normals) {
                result.setNormals(serializationObject.normals);
            }
            if (serializationObject.tangents) {
                result.setTangents(serializationObject.tangents);
            }
            // Animations
            if (serializationObject.animations) {
                for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
                    var parsedAnimation = serializationObject.animations[animationIndex];
                    result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
                }
            }
            return result;
        };
        /**
         * Creates a MorphTarget from mesh data
         * @param mesh defines the source mesh
         * @param name defines the name to use for the new target
         * @param influence defines the influence to attach to the target
         * @returns a new MorphTarget
         */
        MorphTarget.FromMesh = function (mesh, name, influence) {
            if (!name) {
                name = mesh.name;
            }
            var result = new MorphTarget(name, influence, mesh.getScene());
            result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
            }
            if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
                result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
            }
            return result;
        };
        return MorphTarget;
    }());
    BABYLON.MorphTarget = MorphTarget;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.morphTarget.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class is used to deform meshes using morphing between different targets
     * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
     */
    var MorphTargetManager = /** @class */ (function () {
        /**
         * Creates a new MorphTargetManager
         * @param scene defines the current scene
         */
        function MorphTargetManager(scene) {
            if (scene === void 0) { scene = null; }
            this._targets = new Array();
            this._targetInfluenceChangedObservers = new Array();
            this._targetDataLayoutChangedObservers = new Array();
            this._activeTargets = new BABYLON.SmartArray(16);
            this._supportsNormals = false;
            this._supportsTangents = false;
            this._vertexCount = 0;
            this._uniqueId = 0;
            this._tempInfluences = new Array();
            if (!scene) {
                scene = BABYLON.Engine.LastCreatedScene;
            }
            this._scene = scene;
            if (this._scene) {
                this._scene.morphTargetManagers.push(this);
                this._uniqueId = this._scene.getUniqueId();
            }
        }
        Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
            /**
             * Gets the unique ID of this manager
             */
            get: function () {
                return this._uniqueId;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
            /**
             * Gets the number of vertices handled by this manager
             */
            get: function () {
                return this._vertexCount;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
            /**
             * Gets a boolean indicating if this manager supports morphing of normals
             */
            get: function () {
                return this._supportsNormals;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
            /**
             * Gets a boolean indicating if this manager supports morphing of tangents
             */
            get: function () {
                return this._supportsTangents;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
            /**
             * Gets the number of targets stored in this manager
             */
            get: function () {
                return this._targets.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
            /**
             * Gets the number of influencers (ie. the number of targets with influences > 0)
             */
            get: function () {
                return this._activeTargets.length;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(MorphTargetManager.prototype, "influences", {
            /**
             * Gets the list of influences (one per target)
             */
            get: function () {
                return this._influences;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the active target at specified index. An active target is a target with an influence > 0
         * @param index defines the index to check
         * @returns the requested target
         */
        MorphTargetManager.prototype.getActiveTarget = function (index) {
            return this._activeTargets.data[index];
        };
        /**
         * Gets the target at specified index
         * @param index defines the index to check
         * @returns the requested target
         */
        MorphTargetManager.prototype.getTarget = function (index) {
            return this._targets[index];
        };
        /**
         * Add a new target to this manager
         * @param target defines the target to add
         */
        MorphTargetManager.prototype.addTarget = function (target) {
            var _this = this;
            this._targets.push(target);
            this._targetInfluenceChangedObservers.push(target.onInfluenceChanged.add(function (needUpdate) {
                _this._syncActiveTargets(needUpdate);
            }));
            this._targetDataLayoutChangedObservers.push(target._onDataLayoutChanged.add(function () {
                _this._syncActiveTargets(true);
            }));
            this._syncActiveTargets(true);
        };
        /**
         * Removes a target from the manager
         * @param target defines the target to remove
         */
        MorphTargetManager.prototype.removeTarget = function (target) {
            var index = this._targets.indexOf(target);
            if (index >= 0) {
                this._targets.splice(index, 1);
                target.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(index, 1)[0]);
                target._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(index, 1)[0]);
                this._syncActiveTargets(true);
            }
        };
        /**
         * Serializes the current manager into a Serialization object
         * @returns the serialized object
         */
        MorphTargetManager.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.id = this.uniqueId;
            serializationObject.targets = [];
            for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
                var target = _a[_i];
                serializationObject.targets.push(target.serialize());
            }
            return serializationObject;
        };
        MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
            var influenceCount = 0;
            this._activeTargets.reset();
            this._supportsNormals = true;
            this._supportsTangents = true;
            this._vertexCount = 0;
            for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
                var target = _a[_i];
                if (target.influence === 0) {
                    continue;
                }
                this._activeTargets.push(target);
                this._tempInfluences[influenceCount++] = target.influence;
                this._supportsNormals = this._supportsNormals && target.hasNormals;
                this._supportsTangents = this._supportsTangents && target.hasTangents;
                var positions = target.getPositions();
                if (positions) {
                    var vertexCount = positions.length / 3;
                    if (this._vertexCount === 0) {
                        this._vertexCount = vertexCount;
                    }
                    else if (this._vertexCount !== vertexCount) {
                        BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
                        return;
                    }
                }
            }
            if (!this._influences || this._influences.length !== influenceCount) {
                this._influences = new Float32Array(influenceCount);
            }
            for (var index = 0; index < influenceCount; index++) {
                this._influences[index] = this._tempInfluences[index];
            }
            if (needUpdate) {
                this.synchronize();
            }
        };
        /**
         * Syncrhonize the targets with all the meshes using this morph target manager
         */
        MorphTargetManager.prototype.synchronize = function () {
            if (!this._scene) {
                return;
            }
            // Flag meshes as dirty to resync with the active targets
            for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
                var mesh = _a[_i];
                if (mesh.morphTargetManager === this) {
                    mesh._syncGeometryWithMorphTargetManager();
                }
            }
        };
        // Statics
        /**
         * Creates a new MorphTargetManager from serialized data
         * @param serializationObject defines the serialized data
         * @param scene defines the hosting scene
         * @returns the new MorphTargetManager
         */
        MorphTargetManager.Parse = function (serializationObject, scene) {
            var result = new MorphTargetManager(scene);
            result._uniqueId = serializationObject.id;
            for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
                var targetData = _a[_i];
                result.addTarget(BABYLON.MorphTarget.Parse(targetData));
            }
            return result;
        };
        return MorphTargetManager;
    }());
    BABYLON.MorphTargetManager = MorphTargetManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.morphTargetManager.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
     * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
     */
    var Octree = /** @class */ (function () {
        /**
         * Creates a octree
         * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
         * @param creationFunc function to be used to instatiate the octree
         * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
         * @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
         */
        function Octree(creationFunc, maxBlockCapacity, 
        /** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
        maxDepth) {
            if (maxDepth === void 0) { maxDepth = 2; }
            this.maxDepth = maxDepth;
            /**
             * Content stored in the octree
             */
            this.dynamicContent = new Array();
            this._maxBlockCapacity = maxBlockCapacity || 64;
            this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
            this._creationFunc = creationFunc;
        }
        // Methods
        /**
         * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
         * @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
         * @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
         * @param entries meshes to be added to the octree blocks
         */
        Octree.prototype.update = function (worldMin, worldMax, entries) {
            Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
        };
        /**
         * Adds a mesh to the octree
         * @param entry Mesh to add to the octree
         */
        Octree.prototype.addMesh = function (entry) {
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.addEntry(entry);
            }
        };
        /**
         * Selects an array of meshes within the frustum
         * @param frustumPlanes The frustum planes to use which will select all meshes within it
         * @param allowDuplicate If duplicate objects are allowed in the resulting object array
         * @returns array of meshes within the frustum
         */
        Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
            this._selectionContent.reset();
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.select(frustumPlanes, this._selectionContent, allowDuplicate);
            }
            if (allowDuplicate) {
                this._selectionContent.concat(this.dynamicContent);
            }
            else {
                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
            }
            return this._selectionContent;
        };
        /**
         * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
         * @param sphereCenter defines the bounding sphere center
         * @param sphereRadius defines the bounding sphere radius
         * @param allowDuplicate defines if the selection array can contains duplicated entries
         * @returns an array of objects that intersect the sphere
         */
        Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
            this._selectionContent.reset();
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
            }
            if (allowDuplicate) {
                this._selectionContent.concat(this.dynamicContent);
            }
            else {
                this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
            }
            return this._selectionContent;
        };
        /**
        * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
         * @param ray defines the ray to test with
         * @returns array of intersected objects
         */
        Octree.prototype.intersectsRay = function (ray) {
            this._selectionContent.reset();
            for (var index = 0; index < this.blocks.length; index++) {
                var block = this.blocks[index];
                block.intersectsRay(ray, this._selectionContent);
            }
            this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
            return this._selectionContent;
        };
        /**
         * @hidden
         */
        Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
            target.blocks = new Array();
            var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
            // Segmenting space
            for (var x = 0; x < 2; x++) {
                for (var y = 0; y < 2; y++) {
                    for (var z = 0; z < 2; z++) {
                        var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
                        var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
                        var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
                        block.addEntries(entries);
                        target.blocks.push(block);
                    }
                }
            }
        };
        /**
         * Adds a mesh into the octree block if it intersects the block
         */
        Octree.CreationFuncForMeshes = function (entry, block) {
            var boundingInfo = entry.getBoundingInfo();
            if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
                block.entries.push(entry);
            }
        };
        /**
         * Adds a submesh into the octree block if it intersects the block
         */
        Octree.CreationFuncForSubMeshes = function (entry, block) {
            var boundingInfo = entry.getBoundingInfo();
            if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
                block.entries.push(entry);
            }
        };
        return Octree;
    }());
    BABYLON.Octree = Octree;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.octree.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to store a cell in an octree
     * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
     */
    var OctreeBlock = /** @class */ (function () {
        /**
         * Creates a new block
         * @param minPoint defines the minimum vector (in world space) of the block's bounding box
         * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
         * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
         * @param depth defines the current depth of this block in the octree
         * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
         * @param creationFunc defines a callback to call when an element is added to the block
         */
        function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
            /**
             * Gets the content of the current block
             */
            this.entries = new Array();
            this._boundingVectors = new Array();
            this._capacity = capacity;
            this._depth = depth;
            this._maxDepth = maxDepth;
            this._creationFunc = creationFunc;
            this._minPoint = minPoint;
            this._maxPoint = maxPoint;
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors[2].x = maxPoint.x;
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors[3].y = maxPoint.y;
            this._boundingVectors.push(minPoint.clone());
            this._boundingVectors[4].z = maxPoint.z;
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors[5].z = minPoint.z;
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors[6].x = minPoint.x;
            this._boundingVectors.push(maxPoint.clone());
            this._boundingVectors[7].y = minPoint.y;
        }
        Object.defineProperty(OctreeBlock.prototype, "capacity", {
            // Property
            /**
             * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
             */
            get: function () {
                return this._capacity;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OctreeBlock.prototype, "minPoint", {
            /**
             * Gets the minimum vector (in world space) of the block's bounding box
             */
            get: function () {
                return this._minPoint;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
            /**
             * Gets the maximum vector (in world space) of the block's bounding box
             */
            get: function () {
                return this._maxPoint;
            },
            enumerable: true,
            configurable: true
        });
        // Methods
        /**
         * Add a new element to this block
         * @param entry defines the element to add
         */
        OctreeBlock.prototype.addEntry = function (entry) {
            if (this.blocks) {
                for (var index = 0; index < this.blocks.length; index++) {
                    var block = this.blocks[index];
                    block.addEntry(entry);
                }
                return;
            }
            this._creationFunc(entry, this);
            if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
                this.createInnerBlocks();
            }
        };
        /**
         * Add an array of elements to this block
         * @param entries defines the array of elements to add
         */
        OctreeBlock.prototype.addEntries = function (entries) {
            for (var index = 0; index < entries.length; index++) {
                var mesh = entries[index];
                this.addEntry(mesh);
            }
        };
        /**
         * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
         * @param frustumPlanes defines the frustum planes to test
         * @param selection defines the array to store current content if selection is positive
         * @param allowDuplicate defines if the selection array can contains duplicated entries
         */
        OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
            if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
                if (this.blocks) {
                    for (var index = 0; index < this.blocks.length; index++) {
                        var block = this.blocks[index];
                        block.select(frustumPlanes, selection, allowDuplicate);
                    }
                    return;
                }
                if (allowDuplicate) {
                    selection.concat(this.entries);
                }
                else {
                    selection.concatWithNoDuplicate(this.entries);
                }
            }
        };
        /**
         * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
         * @param sphereCenter defines the bounding sphere center
         * @param sphereRadius defines the bounding sphere radius
         * @param selection defines the array to store current content if selection is positive
         * @param allowDuplicate defines if the selection array can contains duplicated entries
         */
        OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
            if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
                if (this.blocks) {
                    for (var index = 0; index < this.blocks.length; index++) {
                        var block = this.blocks[index];
                        block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
                    }
                    return;
                }
                if (allowDuplicate) {
                    selection.concat(this.entries);
                }
                else {
                    selection.concatWithNoDuplicate(this.entries);
                }
            }
        };
        /**
         * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
         * @param ray defines the ray to test with
         * @param selection defines the array to store current content if selection is positive
         */
        OctreeBlock.prototype.intersectsRay = function (ray, selection) {
            if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
                if (this.blocks) {
                    for (var index = 0; index < this.blocks.length; index++) {
                        var block = this.blocks[index];
                        block.intersectsRay(ray, selection);
                    }
                    return;
                }
                selection.concatWithNoDuplicate(this.entries);
            }
        };
        /**
         * Subdivide the content into child blocks (this block will then be empty)
         */
        OctreeBlock.prototype.createInnerBlocks = function () {
            BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
        };
        return OctreeBlock;
    }());
    BABYLON.OctreeBlock = OctreeBlock;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.octreeBlock.js.map

var BABYLON;
(function (BABYLON) {
    BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
        if (maxCapacity === void 0) { maxCapacity = 64; }
        if (maxDepth === void 0) { maxDepth = 2; }
        var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
        if (!component) {
            component = new OctreeSceneComponent(this);
            this._addComponent(component);
        }
        if (!this._selectionOctree) {
            this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
        }
        var worldExtends = this.getWorldExtends();
        // Update octree
        this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
        return this._selectionOctree;
    };
    Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
        get: function () {
            return this._selectionOctree;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
     * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
     * @param maxCapacity defines the maximum size of each block (64 by default)
     * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
     * @returns the new octree
     * @see https://www.babylonjs-playground.com/#NA4OQ#12
     * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
     */
    BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
        if (maxCapacity === void 0) { maxCapacity = 64; }
        if (maxDepth === void 0) { maxDepth = 2; }
        var scene = this.getScene();
        var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
        if (!component) {
            component = new OctreeSceneComponent(scene);
            scene._addComponent(component);
        }
        if (!this._submeshesOctree) {
            this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
        }
        this.computeWorldMatrix(true);
        var boundingInfo = this.getBoundingInfo();
        // Update octree
        var bbox = boundingInfo.boundingBox;
        this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
        return this._submeshesOctree;
    };
    /**
     * Defines the octree scene component responsible to manage any octrees
     * in a given scene.
     */
    var OctreeSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function OctreeSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
            /**
             * Indicates if the meshes have been checked to make sure they are isEnabled()
             */
            this.checksIsEnabled = true;
            this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
            this.scene = scene;
            this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
            this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
            this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
            this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
        }
        /**
         * Registers the component in a given scene
         */
        OctreeSceneComponent.prototype.register = function () {
            var _this = this;
            this.scene.onMeshRemovedObservable.add(function (mesh) {
                var sceneOctree = _this.scene.selectionOctree;
                if (sceneOctree !== undefined && sceneOctree !== null) {
                    var index = sceneOctree.dynamicContent.indexOf(mesh);
                    if (index !== -1) {
                        sceneOctree.dynamicContent.splice(index, 1);
                    }
                }
            });
            this.scene.onMeshImportedObservable.add(function (mesh) {
                var sceneOctree = _this.scene.selectionOctree;
                if (sceneOctree !== undefined && sceneOctree !== null) {
                    sceneOctree.addMesh(mesh);
                }
            });
        };
        /**
         * Return the list of active meshes
         * @returns the list of active meshes
         */
        OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
            if (this.scene._selectionOctree) {
                var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
                return selection;
            }
            return this.scene._getDefaultMeshCandidates();
        };
        /**
         * Return the list of active sub meshes
         * @param mesh The mesh to get the candidates sub meshes from
         * @returns the list of active sub meshes
         */
        OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
            if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
                var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
                return intersections;
            }
            return this.scene._getDefaultSubMeshCandidates(mesh);
        };
        /**
         * Return the list of sub meshes intersecting with a given local ray
         * @param mesh defines the mesh to find the submesh for
         * @param localRay defines the ray in local space
         * @returns the list of intersecting sub meshes
         */
        OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
            if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
                BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
                var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
                return intersections;
            }
            return this.scene._getDefaultSubMeshCandidates(mesh);
        };
        /**
         * Return the list of sub meshes colliding with a collider
         * @param mesh defines the mesh to find the submesh for
         * @param collider defines the collider to evaluate the collision against
         * @returns the list of colliding sub meshes
         */
        OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
            if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
                var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
                var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
                return intersections;
            }
            return this.scene._getDefaultSubMeshCandidates(mesh);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        OctreeSceneComponent.prototype.rebuild = function () {
            // Nothing to do here.
        };
        /**
         * Disposes the component and the associated ressources.
         */
        OctreeSceneComponent.prototype.dispose = function () {
            // Nothing to do here.
        };
        return OctreeSceneComponent;
    }());
    BABYLON.OctreeSceneComponent = OctreeSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.octreeSceneComponent.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Postprocess used to generate anaglyphic rendering
     */
    var AnaglyphPostProcess = /** @class */ (function (_super) {
        __extends(AnaglyphPostProcess, _super);
        /**
         * Creates a new AnaglyphPostProcess
         * @param name defines postprocess name
         * @param options defines creation options or target ratio scale
         * @param rigCameras defines cameras using this postprocess
         * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
         * @param engine defines hosting engine
         * @param reusable defines if the postprocess will be reused multiple times per frame
         */
        function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
            var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
            _this._passedProcess = rigCameras[0]._rigPostProcess;
            _this.onApplyObservable.add(function (effect) {
                effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
            });
            return _this;
        }
        return AnaglyphPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.anaglyphPostProcess.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
        return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
    });
    /**
     * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
     * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
     */
    var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
        __extends(AnaglyphArcRotateCamera, _super);
        /**
         * Creates a new AnaglyphArcRotateCamera
         * @param name defines camera name
         * @param alpha defines alpha angle (in radians)
         * @param beta defines beta angle (in radians)
         * @param radius defines radius
         * @param target defines camera target
         * @param interaxialDistance defines distance between each color axis
         * @param scene defines the hosting scene
         */
        function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
            var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns AnaglyphArcRotateCamera
         */
        AnaglyphArcRotateCamera.prototype.getClassName = function () {
            return "AnaglyphArcRotateCamera";
        };
        return AnaglyphArcRotateCamera;
    }(BABYLON.ArcRotateCamera));
    BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
        return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
    });
    /**
     * Camera used to simulate anaglyphic rendering (based on FreeCamera)
     * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
     */
    var AnaglyphFreeCamera = /** @class */ (function (_super) {
        __extends(AnaglyphFreeCamera, _super);
        /**
         * Creates a new AnaglyphFreeCamera
         * @param name defines camera name
         * @param position defines initial position
         * @param interaxialDistance defines distance between each color axis
         * @param scene defines the hosting scene
         */
        function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns AnaglyphFreeCamera
         */
        AnaglyphFreeCamera.prototype.getClassName = function () {
            return "AnaglyphFreeCamera";
        };
        return AnaglyphFreeCamera;
    }(BABYLON.FreeCamera));
    BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.anaglyphFreeCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
        return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
    });
    /**
     * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
     * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
     */
    var AnaglyphGamepadCamera = /** @class */ (function (_super) {
        __extends(AnaglyphGamepadCamera, _super);
        /**
         * Creates a new AnaglyphGamepadCamera
         * @param name defines camera name
         * @param position defines initial position
         * @param interaxialDistance defines distance between each color axis
         * @param scene defines the hosting scene
         */
        function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns AnaglyphGamepadCamera
         */
        AnaglyphGamepadCamera.prototype.getClassName = function () {
            return "AnaglyphGamepadCamera";
        };
        return AnaglyphGamepadCamera;
    }(BABYLON.GamepadCamera));
    BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
        return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
    });
    /**
     * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
     * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
     */
    var AnaglyphUniversalCamera = /** @class */ (function (_super) {
        __extends(AnaglyphUniversalCamera, _super);
        /**
         * Creates a new AnaglyphUniversalCamera
         * @param name defines camera name
         * @param position defines initial position
         * @param interaxialDistance defines distance between each color axis
         * @param scene defines the hosting scene
         */
        function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns AnaglyphUniversalCamera
         */
        AnaglyphUniversalCamera.prototype.getClassName = function () {
            return "AnaglyphUniversalCamera";
        };
        return AnaglyphUniversalCamera;
    }(BABYLON.UniversalCamera));
    BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
     */
    var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
        __extends(StereoscopicInterlacePostProcess, _super);
        /**
         * Initializes a StereoscopicInterlacePostProcess
         * @param name The name of the effect.
         * @param rigCameras The rig cameras to be appled to the post process
         * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
         * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
         * @param engine The engine which the post process will be applied. (default: current engine)
         * @param reusable If the post process can be reused on the same frame. (default: false)
         */
        function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
            var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
            _this._passedProcess = rigCameras[0]._rigPostProcess;
            _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
            _this.onSizeChangedObservable.add(function () {
                _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
            });
            _this.onApplyObservable.add(function (effect) {
                effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
                effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
            });
            return _this;
        }
        return StereoscopicInterlacePostProcess;
    }(BABYLON.PostProcess));
    BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
        return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
    });
    /**
     * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
     * @see http://doc.babylonjs.com/features/cameras
     */
    var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
        __extends(StereoscopicArcRotateCamera, _super);
        /**
         * Creates a new StereoscopicArcRotateCamera
         * @param name defines camera name
         * @param alpha defines alpha angle (in radians)
         * @param beta defines beta angle (in radians)
         * @param radius defines radius
         * @param target defines camera target
         * @param interaxialDistance defines distance between each color axis
         * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
         * @param scene defines the hosting scene
         */
        function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
            var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns StereoscopicArcRotateCamera
         */
        StereoscopicArcRotateCamera.prototype.getClassName = function () {
            return "StereoscopicArcRotateCamera";
        };
        return StereoscopicArcRotateCamera;
    }(BABYLON.ArcRotateCamera));
    BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
        return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
    });
    /**
     * Camera used to simulate stereoscopic rendering (based on FreeCamera)
     * @see http://doc.babylonjs.com/features/cameras
     */
    var StereoscopicFreeCamera = /** @class */ (function (_super) {
        __extends(StereoscopicFreeCamera, _super);
        /**
         * Creates a new StereoscopicFreeCamera
         * @param name defines camera name
         * @param position defines initial position
         * @param interaxialDistance defines distance between each color axis
         * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
         * @param scene defines the hosting scene
         */
        function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns StereoscopicFreeCamera
         */
        StereoscopicFreeCamera.prototype.getClassName = function () {
            return "StereoscopicFreeCamera";
        };
        return StereoscopicFreeCamera;
    }(BABYLON.FreeCamera));
    BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
        return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
    });
    /**
     * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
     * @see http://doc.babylonjs.com/features/cameras
     */
    var StereoscopicGamepadCamera = /** @class */ (function (_super) {
        __extends(StereoscopicGamepadCamera, _super);
        /**
         * Creates a new StereoscopicGamepadCamera
         * @param name defines camera name
         * @param position defines initial position
         * @param interaxialDistance defines distance between each color axis
         * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
         * @param scene defines the hosting scene
         */
        function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns StereoscopicGamepadCamera
         */
        StereoscopicGamepadCamera.prototype.getClassName = function () {
            return "StereoscopicGamepadCamera";
        };
        return StereoscopicGamepadCamera;
    }(BABYLON.GamepadCamera));
    BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
        return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
    });
    /**
     * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
     * @see http://doc.babylonjs.com/features/cameras
     */
    var StereoscopicUniversalCamera = /** @class */ (function (_super) {
        __extends(StereoscopicUniversalCamera, _super);
        /**
         * Creates a new StereoscopicUniversalCamera
         * @param name defines camera name
         * @param position defines initial position
         * @param interaxialDistance defines distance between each color axis
         * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
         * @param scene defines the hosting scene
         */
        function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.interaxialDistance = interaxialDistance;
            _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
            _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns StereoscopicUniversalCamera
         */
        StereoscopicUniversalCamera.prototype.getClassName = function () {
            return "StereoscopicUniversalCamera";
        };
        return StereoscopicUniversalCamera;
    }(BABYLON.UniversalCamera));
    BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * VRDistortionCorrectionPostProcess used for mobile VR
     */
    var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
        __extends(VRDistortionCorrectionPostProcess, _super);
        /**
         * Initializes the VRDistortionCorrectionPostProcess
         * @param name The name of the effect.
         * @param camera The camera to apply the render pass to.
         * @param isRightEye If this is for the right eye distortion
         * @param vrMetrics All the required metrics for the VR camera
         */
        function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
            var _this = _super.call(this, name, "vrDistortionCorrection", [
                'LensCenter',
                'Scale',
                'ScaleIn',
                'HmdWarpParam'
            ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
            _this._isRightEye = isRightEye;
            _this._distortionFactors = vrMetrics.distortionK;
            _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
            _this._lensCenterOffset = vrMetrics.lensCenterOffset;
            _this.adaptScaleToCurrentViewport = true;
            _this.onSizeChangedObservable.add(function () {
                _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
                _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
                _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
            });
            _this.onApplyObservable.add(function (effect) {
                effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
                effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
                effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
                effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
            });
            return _this;
        }
        return VRDistortionCorrectionPostProcess;
    }(BABYLON.PostProcess));
    BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
     * Screen rotation is taken into account.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraDeviceOrientationInput = /** @class */ (function () {
        /**
         * Instantiates a new input
         * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
         */
        function FreeCameraDeviceOrientationInput() {
            var _this = this;
            this._screenOrientationAngle = 0;
            this._screenQuaternion = new BABYLON.Quaternion();
            this._alpha = 0;
            this._beta = 0;
            this._gamma = 0;
            this._orientationChanged = function () {
                _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
                _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
                _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
            };
            this._deviceOrientation = function (evt) {
                _this._alpha = evt.alpha !== null ? evt.alpha : 0;
                _this._beta = evt.beta !== null ? evt.beta : 0;
                _this._gamma = evt.gamma !== null ? evt.gamma : 0;
            };
            this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
            this._orientationChanged();
        }
        Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
            /**
             * Define the camera controlled by the input.
             */
            get: function () {
                return this._camera;
            },
            set: function (camera) {
                this._camera = camera;
                if (this._camera != null && !this._camera.rotationQuaternion) {
                    this._camera.rotationQuaternion = new BABYLON.Quaternion();
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
            window.addEventListener("orientationchange", this._orientationChanged);
            window.addEventListener("deviceorientation", this._deviceOrientation);
            //In certain cases, the attach control is called AFTER orientation was changed,
            //So this is needed.
            this._orientationChanged();
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
            window.removeEventListener("orientationchange", this._orientationChanged);
            window.removeEventListener("deviceorientation", this._deviceOrientation);
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
            //if no device orientation provided, don't update the rotation.
            //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
            if (!this._alpha) {
                return;
            }
            BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
            this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
            this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
            //Mirror on XY Plane
            this._camera.rotationQuaternion.z *= -1;
            this._camera.rotationQuaternion.w *= -1;
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
            return "FreeCameraDeviceOrientationInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
            return "deviceOrientation";
        };
        return FreeCameraDeviceOrientationInput;
    }());
    BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
    BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
        /**
         * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
         */
        function ArcRotateCameraVRDeviceOrientationInput() {
            /**
             * Defines a correction factor applied on the alpha value retrieved from the orientation events.
             */
            this.alphaCorrection = 1;
            /**
             * Defines a correction factor applied on the beta value retrieved from the orientation events.
             */
            this.betaCorrection = 1;
            /**
             * Defines a correction factor applied on the gamma value retrieved from the orientation events.
             */
            this.gammaCorrection = 1;
            this._alpha = 0;
            this._gamma = 0;
            this._dirty = false;
            this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
        }
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
            this.camera.attachControl(element, noPreventDefault);
            window.addEventListener("deviceorientation", this._deviceOrientationHandler);
        };
        /** @hidden */
        ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
            if (evt.alpha !== null) {
                this._alpha = +evt.alpha | 0;
            }
            if (evt.gamma !== null) {
                this._gamma = +evt.gamma | 0;
            }
            this._dirty = true;
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
            if (this._dirty) {
                this._dirty = false;
                if (this._gamma < 0) {
                    this._gamma = 180 + this._gamma;
                }
                this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
                this.camera.beta = (this._gamma / 180.0 * Math.PI);
            }
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
            window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
            return "ArcRotateCameraVRDeviceOrientationInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
            return "VRDeviceOrientation";
        };
        return ArcRotateCameraVRDeviceOrientationInput;
    }());
    BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
    BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents all the required metrics to create a VR camera.
     * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
     */
    var VRCameraMetrics = /** @class */ (function () {
        function VRCameraMetrics() {
            /**
             * Define if the current vr camera should compensate the distortion of the lense or not.
             */
            this.compensateDistortion = true;
        }
        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
            /**
             * Gets the rendering aspect ratio based on the provided resolutions.
             */
            get: function () {
                return this.hResolution / (2 * this.vResolution);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
            /**
             * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
             */
            get: function () {
                return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
            /**
             * @hidden
             */
            get: function () {
                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
                var h = (4 * meters) / this.hScreenSize;
                return BABYLON.Matrix.Translation(h, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
            /**
             * @hidden
             */
            get: function () {
                var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
                var h = (4 * meters) / this.hScreenSize;
                return BABYLON.Matrix.Translation(-h, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
            /**
             * @hidden
             */
            get: function () {
                return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
            /**
             * @hidden
             */
            get: function () {
                return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get the default VRMetrics based on the most generic setup.
         * @returns the default vr metrics
         */
        VRCameraMetrics.GetDefault = function () {
            var result = new VRCameraMetrics();
            result.hResolution = 1280;
            result.vResolution = 800;
            result.hScreenSize = 0.149759993;
            result.vScreenSize = 0.0935999975;
            result.vScreenCenter = 0.0467999987;
            result.eyeToScreenDistance = 0.0410000011;
            result.lensSeparationDistance = 0.0635000020;
            result.interpupillaryDistance = 0.0640000030;
            result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
            result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
            result.postProcessScaleFactor = 1.714605507808412;
            result.lensCenterOffset = 0.151976421;
            return result;
        };
        return VRCameraMetrics;
    }());
    BABYLON.VRCameraMetrics = VRCameraMetrics;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vrCameraMetrics.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
        return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
        return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * This represents a WebVR camera.
     * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
     * @example http://doc.babylonjs.com/how_to/webvr_camera
     */
    var WebVRFreeCamera = /** @class */ (function (_super) {
        __extends(WebVRFreeCamera, _super);
        /**
         * Instantiates a WebVRFreeCamera.
         * @param name The name of the WebVRFreeCamera
         * @param position The starting anchor position for the camera
         * @param scene The scene the camera belongs to
         * @param webVROptions a set of customizable options for the webVRCamera
         */
        function WebVRFreeCamera(name, position, scene, webVROptions) {
            if (webVROptions === void 0) { webVROptions = {}; }
            var _this = _super.call(this, name, position, scene) || this;
            _this.webVROptions = webVROptions;
            /**
             * @hidden
             * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
             */
            _this._vrDevice = null;
            /**
             * The rawPose of the vrDevice.
             */
            _this.rawPose = null;
            _this._specsVersion = "1.1";
            _this._attached = false;
            _this._descendants = [];
            // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
            _this._deviceRoomPosition = BABYLON.Vector3.Zero();
            /** @hidden */
            _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
            _this._standingMatrix = null;
            /**
             * Represents device position in babylon space.
             */
            _this.devicePosition = BABYLON.Vector3.Zero();
            /**
             * Represents device rotation in babylon space.
             */
            _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
            /**
             * The scale of the device to be used when translating from device space to babylon space.
             */
            _this.deviceScaleFactor = 1;
            _this._deviceToWorld = BABYLON.Matrix.Identity();
            _this._worldToDevice = BABYLON.Matrix.Identity();
            /**
             * References to the webVR controllers for the vrDevice.
             */
            _this.controllers = [];
            /**
             * Emits an event when a controller is attached.
             */
            _this.onControllersAttachedObservable = new BABYLON.Observable();
            /**
             * Emits an event when a controller's mesh has been loaded;
             */
            _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
            /**
             * Emits an event when the HMD's pose has been updated.
             */
            _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
            _this._poseSet = false;
            /**
             * If the rig cameras be used as parent instead of this camera.
             */
            _this.rigParenting = true;
            _this._defaultHeight = undefined;
            _this._htmlElementAttached = null;
            _this._detachIfAttached = function () {
                var vrDisplay = _this.getEngine().getVRDevice();
                if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
                    _this.detachControl(_this._htmlElementAttached);
                }
            };
            _this._workingVector = BABYLON.Vector3.Zero();
            _this._oneVector = BABYLON.Vector3.One();
            _this._workingMatrix = BABYLON.Matrix.Identity();
            _this._tmpMatrix = new BABYLON.Matrix();
            _this._cache.position = BABYLON.Vector3.Zero();
            if (webVROptions.defaultHeight) {
                _this._defaultHeight = webVROptions.defaultHeight;
                _this.position.y = _this._defaultHeight;
            }
            _this.minZ = 0.1;
            //legacy support - the compensation boolean was removed.
            if (arguments.length === 5) {
                _this.webVROptions = arguments[4];
            }
            // default webVR options
            if (_this.webVROptions.trackPosition == undefined) {
                _this.webVROptions.trackPosition = true;
            }
            if (_this.webVROptions.controllerMeshes == undefined) {
                _this.webVROptions.controllerMeshes = true;
            }
            if (_this.webVROptions.defaultLightingOnControllers == undefined) {
                _this.webVROptions.defaultLightingOnControllers = true;
            }
            _this.rotationQuaternion = new BABYLON.Quaternion();
            if (_this.webVROptions && _this.webVROptions.positionScale) {
                _this.deviceScaleFactor = _this.webVROptions.positionScale;
            }
            //enable VR
            var engine = _this.getEngine();
            _this._onVREnabled = function (success) { if (success) {
                _this.initControllers();
            } };
            engine.onVRRequestPresentComplete.add(_this._onVREnabled);
            engine.initWebVR().add(function (event) {
                if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
                    return;
                }
                _this._vrDevice = event.vrDisplay;
                //reset the rig parameters.
                _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
                if (_this._attached) {
                    _this.getEngine().enableVR();
                }
            });
            if (typeof (VRFrameData) !== "undefined") {
                _this._frameData = new VRFrameData();
            }
            /**
             * The idea behind the following lines:
             * objects that have the camera as parent should actually have the rig cameras as a parent.
             * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
             * the second will not show it correctly.
             *
             * To solve this - each object that has the camera as parent will be added to a protected array.
             * When the rig camera renders, it will take this array and set all of those to be its children.
             * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
             * Amazing!
             */
            scene.onBeforeCameraRenderObservable.add(function (camera) {
                if (camera.parent === _this && _this.rigParenting) {
                    _this._descendants = _this.getDescendants(true, function (n) {
                        // don't take the cameras or the controllers!
                        var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
                        var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
                        return !isController && !isRigCamera;
                    });
                    _this._descendants.forEach(function (node) {
                        node.parent = camera;
                    });
                }
            });
            scene.onAfterCameraRenderObservable.add(function (camera) {
                if (camera.parent === _this && _this.rigParenting) {
                    _this._descendants.forEach(function (node) {
                        node.parent = _this;
                    });
                }
            });
            return _this;
        }
        /**
         * Gets the device distance from the ground in meters.
         * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
         */
        WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
            if (this._standingMatrix) {
                // Add standing matrix offset to get real offset from ground in room
                this._standingMatrix.getTranslationToRef(this._workingVector);
                return this._deviceRoomPosition.y + this._workingVector.y;
            }
            //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
            return this._defaultHeight || 0;
        };
        /**
         * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
         * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
         */
        WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
            var _this = this;
            if (callback === void 0) { callback = function (bool) { }; }
            // Use standing matrix if available
            this.getEngine().initWebVRAsync().then(function (result) {
                if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
                    callback(false);
                }
                else {
                    _this._standingMatrix = new BABYLON.Matrix();
                    BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
                    if (!_this.getScene().useRightHandedSystem) {
                        [2, 6, 8, 9, 14].forEach(function (num) {
                            if (_this._standingMatrix) {
                                _this._standingMatrix.m[num] *= -1;
                            }
                        });
                    }
                    callback(true);
                }
            });
        };
        /**
         * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
         * @returns A promise with a boolean set to if the standing matrix is supported.
         */
        WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
            var _this = this;
            return new Promise(function (res, rej) {
                _this.useStandingMatrix(function (supported) {
                    res(supported);
                });
            });
        };
        /**
         * Disposes the camera
         */
        WebVRFreeCamera.prototype.dispose = function () {
            this._detachIfAttached();
            this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
            if (this._updateCacheWhenTrackingDisabledObserver) {
                this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
            }
            _super.prototype.dispose.call(this);
        };
        /**
         * Gets a vrController by name.
         * @param name The name of the controller to retreive
         * @returns the controller matching the name specified or null if not found
         */
        WebVRFreeCamera.prototype.getControllerByName = function (name) {
            for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
                var gp = _a[_i];
                if (gp.hand === name) {
                    return gp;
                }
            }
            return null;
        };
        Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
            /**
             * The controller corrisponding to the users left hand.
             */
            get: function () {
                if (!this._leftController) {
                    this._leftController = this.getControllerByName("left");
                }
                return this._leftController;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
            /**
             * The controller corrisponding to the users right hand.
             */
            get: function () {
                if (!this._rightController) {
                    this._rightController = this.getControllerByName("right");
                }
                return this._rightController;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Casts a ray forward from the vrCamera's gaze.
         * @param length Length of the ray (default: 100)
         * @returns the ray corrisponding to the gaze
         */
        WebVRFreeCamera.prototype.getForwardRay = function (length) {
            if (length === void 0) { length = 100; }
            if (this.leftCamera) {
                // Use left eye to avoid computation to compute center on every call
                return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
            }
            else {
                return _super.prototype.getForwardRay.call(this, length);
            }
        };
        /**
         * @hidden
         * Updates the camera based on device's frame data
         */
        WebVRFreeCamera.prototype._checkInputs = function () {
            if (this._vrDevice && this._vrDevice.isPresenting) {
                this._vrDevice.getFrameData(this._frameData);
                this.updateFromDevice(this._frameData.pose);
            }
            _super.prototype._checkInputs.call(this);
        };
        /**
         * Updates the poseControlled values based on the input device pose.
         * @param poseData Pose coming from the device
         */
        WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
            if (poseData && poseData.orientation) {
                this.rawPose = poseData;
                this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
                if (this.getScene().useRightHandedSystem) {
                    this._deviceRoomRotationQuaternion.z *= -1;
                    this._deviceRoomRotationQuaternion.w *= -1;
                }
                if (this.webVROptions.trackPosition && this.rawPose.position) {
                    this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
                    if (this.getScene().useRightHandedSystem) {
                        this._deviceRoomPosition.z *= -1;
                    }
                }
                this._poseSet = true;
            }
        };
        /**
         * WebVR's attach control will start broadcasting frames to the device.
         * Note that in certain browsers (chrome for example) this function must be called
         * within a user-interaction callback. Example:
         * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
         *
         * @param element html element to attach the vrDevice to
         * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
         */
        WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
            _super.prototype.attachControl.call(this, element, noPreventDefault);
            this._attached = true;
            this._htmlElementAttached = element;
            noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
            if (this._vrDevice) {
                this.getEngine().enableVR();
            }
            window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
        };
        /**
         * Detaches the camera from the html element and disables VR
         *
         * @param element html element to detach from
         */
        WebVRFreeCamera.prototype.detachControl = function (element) {
            this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
            this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
            _super.prototype.detachControl.call(this, element);
            this._attached = false;
            this.getEngine().disableVR();
            window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
        };
        /**
         * @returns the name of this class
         */
        WebVRFreeCamera.prototype.getClassName = function () {
            return "WebVRFreeCamera";
        };
        /**
         * Calls resetPose on the vrDisplay
         * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
         */
        WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
            //uses the vrDisplay's "resetPose()".
            //pitch and roll won't be affected.
            this._vrDevice.resetPose();
        };
        /**
         * @hidden
         * Updates the rig cameras (left and right eye)
         */
        WebVRFreeCamera.prototype._updateRigCameras = function () {
            var camLeft = this._rigCameras[0];
            var camRight = this._rigCameras[1];
            camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
            camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
            camLeft.position.copyFrom(this._deviceRoomPosition);
            camRight.position.copyFrom(this._deviceRoomPosition);
        };
        // Remove translation from 6dof headset if trackposition is set to false
        WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
            if (isViewMatrix === void 0) { isViewMatrix = false; }
            if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
                BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
                if (!isViewMatrix) {
                    this._tmpMatrix.invert();
                }
                this._tmpMatrix.multiplyToRef(matrix, matrix);
            }
        };
        /**
         * @hidden
         * Updates the cached values of the camera
         * @param ignoreParentClass ignores updating the parent class's cache (default: false)
         */
        WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
            var _this = this;
            if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
                // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
                if (!this.updateCacheCalled) {
                    // make sure it is only called once per loop. this.update() might cause an infinite loop.
                    this.updateCacheCalled = true;
                    this.update();
                }
                // Set working vector to the device position in room space rotated by the new rotation
                this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
                BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
                // Subtract this vector from the current device position in world to get the translation for the device world matrix
                this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
                BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
                // Add translation from anchor position
                this._deviceToWorld.getTranslationToRef(this._workingVector);
                this._workingVector.addInPlace(this.position);
                this._workingVector.subtractInPlace(this._cache.position);
                this._deviceToWorld.setTranslation(this._workingVector);
                // Set an inverted matrix to be used when updating the camera
                this._deviceToWorld.invertToRef(this._worldToDevice);
                // Update the gamepad to ensure the mesh is updated on the same frame as camera
                this.controllers.forEach(function (controller) {
                    controller._deviceToWorld.copyFrom(_this._deviceToWorld);
                    _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
                    controller.update();
                });
            }
            if (!ignoreParentClass) {
                _super.prototype._updateCache.call(this);
            }
            this.updateCacheCalled = false;
        };
        /**
         * @hidden
         * Get current device position in babylon world
         */
        WebVRFreeCamera.prototype._computeDevicePosition = function () {
            BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
        };
        /**
         * Updates the current device position and rotation in the babylon world
         */
        WebVRFreeCamera.prototype.update = function () {
            this._computeDevicePosition();
            // Get current device rotation in babylon world
            BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
            this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
            BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
            if (this._poseSet) {
                this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
            }
            _super.prototype.update.call(this);
        };
        /**
         * @hidden
         * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
         * @returns an identity matrix
         */
        WebVRFreeCamera.prototype._getViewMatrix = function () {
            return BABYLON.Matrix.Identity();
        };
        /**
         * This function is called by the two RIG cameras.
         * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
         */
        WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
            var _this = this;
            // Update the parent camera prior to using a child camera to avoid desynchronization
            var parentCamera = this._cameraRigParams["parentCamera"];
            parentCamera._updateCache();
            //WebVR 1.1
            var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
            BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
            if (!this.getScene().useRightHandedSystem) {
                [2, 6, 8, 9, 14].forEach(function (num) {
                    _this._webvrViewMatrix.m[num] *= -1;
                });
            }
            // update the camera rotation matrix
            this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
            BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
            // Computing target and final matrix
            this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
            // should the view matrix be updated with scale and position offset?
            if (parentCamera.deviceScaleFactor !== 1) {
                this._webvrViewMatrix.invert();
                // scale the position, if set
                if (parentCamera.deviceScaleFactor) {
                    this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
                    this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
                    this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
                }
                this._webvrViewMatrix.invert();
            }
            // Remove translation from 6dof headset if trackposition is set to false
            parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
            parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
            // Compute global position
            this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
            this._webvrViewMatrix.invertToRef(this._workingMatrix);
            this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
            this._workingMatrix.getTranslationToRef(this._globalPosition);
            this._markSyncedWithParent();
            return this._webvrViewMatrix;
        };
        WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
            var _this = this;
            var parentCamera = this.parent;
            parentCamera._vrDevice.depthNear = parentCamera.minZ;
            parentCamera._vrDevice.depthFar = parentCamera.maxZ;
            var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
            BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
            //babylon compatible matrix
            if (!this.getScene().useRightHandedSystem) {
                [8, 9, 10, 11].forEach(function (num) {
                    _this._projectionMatrix.m[num] *= -1;
                });
            }
            return this._projectionMatrix;
        };
        /**
         * Initializes the controllers and their meshes
         */
        WebVRFreeCamera.prototype.initControllers = function () {
            var _this = this;
            this.controllers = [];
            var manager = this.getScene().gamepadManager;
            this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
                if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
                    var webVrController = gamepad;
                    if (webVrController.defaultModel) {
                        webVrController.defaultModel.setEnabled(false);
                    }
                    if (webVrController.hand === "right") {
                        _this._rightController = null;
                    }
                    if (webVrController.hand === "left") {
                        _this._leftController = null;
                    }
                    var controllerIndex = _this.controllers.indexOf(webVrController);
                    if (controllerIndex !== -1) {
                        _this.controllers.splice(controllerIndex, 1);
                    }
                }
            });
            this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
                if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
                    var webVrController_1 = gamepad;
                    if (!_this.webVROptions.trackPosition) {
                        webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
                        // Cache must be updated before rendering controllers to avoid them being one frame behind
                        if (!_this._updateCacheWhenTrackingDisabledObserver) {
                            _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
                                _this._updateCache();
                            });
                        }
                    }
                    webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
                    webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
                    _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
                    if (_this.webVROptions.controllerMeshes) {
                        if (webVrController_1.defaultModel) {
                            webVrController_1.defaultModel.setEnabled(true);
                        }
                        else {
                            // Load the meshes
                            webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
                                loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
                                _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
                                if (_this.webVROptions.defaultLightingOnControllers) {
                                    if (!_this._lightOnControllers) {
                                        _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
                                    }
                                    var activateLightOnSubMeshes_1 = function (mesh, light) {
                                        var children = mesh.getChildren();
                                        if (children && children.length !== 0) {
                                            children.forEach(function (mesh) {
                                                light.includedOnlyMeshes.push(mesh);
                                                activateLightOnSubMeshes_1(mesh, light);
                                            });
                                        }
                                    };
                                    _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
                                    activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
                                }
                            });
                        }
                    }
                    webVrController_1.attachToPoseControlledCamera(_this);
                    // since this is async - sanity check. Is the controller already stored?
                    if (_this.controllers.indexOf(webVrController_1) === -1) {
                        //add to the controllers array
                        _this.controllers.push(webVrController_1);
                        // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
                        // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
                        // So we're overriding setting left & right manually to be sure
                        var firstViveWandDetected = false;
                        for (var i = 0; i < _this.controllers.length; i++) {
                            if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
                                if (!firstViveWandDetected) {
                                    firstViveWandDetected = true;
                                    _this.controllers[i].hand = "left";
                                }
                                else {
                                    _this.controllers[i].hand = "right";
                                }
                            }
                        }
                        //did we find enough controllers? Great! let the developer know.
                        if (_this.controllers.length >= 2) {
                            _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
                        }
                    }
                }
            });
        };
        return WebVRFreeCamera;
    }(BABYLON.FreeCamera));
    BABYLON.WebVRFreeCamera = WebVRFreeCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.webVRCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
        return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    // We're mainly based on the logic defined into the FreeCamera code
    /**
     * This is a camera specifically designed to react to device orientation events such as a modern mobile device
     * being tilted forward or back and left or right.
     */
    var DeviceOrientationCamera = /** @class */ (function (_super) {
        __extends(DeviceOrientationCamera, _super);
        /**
         * Creates a new device orientation camera
         * @param name The name of the camera
         * @param position The start position camera
         * @param scene The scene the camera belongs to
         */
        function DeviceOrientationCamera(name, position, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this._quaternionCache = new BABYLON.Quaternion();
            _this.inputs.addDeviceOrientation();
            return _this;
        }
        /**
         * Gets the current instance class name ("DeviceOrientationCamera").
         * This helps avoiding instanceof at run time.
         * @returns the class name
         */
        DeviceOrientationCamera.prototype.getClassName = function () {
            return "DeviceOrientationCamera";
        };
        /**
         * @hidden
         * Checks and applies the current values of the inputs to the camera. (Internal use only)
         */
        DeviceOrientationCamera.prototype._checkInputs = function () {
            _super.prototype._checkInputs.call(this);
            this._quaternionCache.copyFrom(this.rotationQuaternion);
            if (this._initialQuaternion) {
                this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
            }
        };
        /**
         * Reset the camera to its default orientation on the specified axis only.
         * @param axis The axis to reset
         */
        DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
            var _this = this;
            if (axis === void 0) { axis = BABYLON.Axis.Y; }
            //can only work if this camera has a rotation quaternion already.
            if (!this.rotationQuaternion) {
                return;
            }
            if (!this._initialQuaternion) {
                this._initialQuaternion = new BABYLON.Quaternion();
            }
            this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
            ['x', 'y', 'z'].forEach(function (axisName) {
                if (!axis[axisName]) {
                    _this._initialQuaternion[axisName] = 0;
                }
                else {
                    _this._initialQuaternion[axisName] *= -1;
                }
            });
            this._initialQuaternion.normalize();
            //force rotation update
            this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
        };
        return DeviceOrientationCamera;
    }(BABYLON.FreeCamera));
    BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.deviceOrientationCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
        return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * Camera used to simulate VR rendering (based on FreeCamera)
     * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
     */
    var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
        __extends(VRDeviceOrientationFreeCamera, _super);
        /**
         * Creates a new VRDeviceOrientationFreeCamera
         * @param name defines camera name
         * @param position defines the start position of the camera
         * @param scene defines the scene the camera belongs to
         * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
         * @param vrCameraMetrics defines the vr metrics associated to the camera
         */
        function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
            if (compensateDistortion === void 0) { compensateDistortion = true; }
            if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
            var _this = _super.call(this, name, position, scene) || this;
            vrCameraMetrics.compensateDistortion = compensateDistortion;
            _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
            return _this;
        }
        /**
         * Gets camera class name
         * @returns VRDeviceOrientationFreeCamera
         */
        VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
            return "VRDeviceOrientationFreeCamera";
        };
        return VRDeviceOrientationFreeCamera;
    }(BABYLON.DeviceOrientationCamera));
    BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
        return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * Camera used to simulate VR rendering (based on ArcRotateCamera)
     * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
     */
    var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
        __extends(VRDeviceOrientationArcRotateCamera, _super);
        /**
         * Creates a new VRDeviceOrientationArcRotateCamera
         * @param name defines camera name
         * @param alpha defines the camera rotation along the logitudinal axis
         * @param beta defines the camera rotation along the latitudinal axis
         * @param radius defines the camera distance from its target
         * @param target defines the camera target
         * @param scene defines the scene the camera belongs to
         * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
         * @param vrCameraMetrics defines the vr metrics associated to the camera
         */
        function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
            if (compensateDistortion === void 0) { compensateDistortion = true; }
            if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
            var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
            vrCameraMetrics.compensateDistortion = compensateDistortion;
            _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
            _this.inputs.addVRDeviceOrientation();
            return _this;
        }
        /**
         * Gets camera class name
         * @returns VRDeviceOrientationArcRotateCamera
         */
        VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
            return "VRDeviceOrientationArcRotateCamera";
        };
        return VRDeviceOrientationArcRotateCamera;
    }(BABYLON.ArcRotateCamera));
    BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
        return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
     * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
     */
    var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
        __extends(VRDeviceOrientationGamepadCamera, _super);
        /**
         * Creates a new VRDeviceOrientationGamepadCamera
         * @param name defines camera name
         * @param position defines the start position of the camera
         * @param scene defines the scene the camera belongs to
         * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
         * @param vrCameraMetrics defines the vr metrics associated to the camera
         */
        function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
            if (compensateDistortion === void 0) { compensateDistortion = true; }
            if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
            var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
            _this.inputs.addGamepad();
            return _this;
        }
        /**
         * Gets camera class name
         * @returns VRDeviceOrientationGamepadCamera
         */
        VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
            return "VRDeviceOrientationGamepadCamera";
        };
        return VRDeviceOrientationGamepadCamera;
    }(BABYLON.VRDeviceOrientationFreeCamera));
    BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map


var BABYLON;
(function (BABYLON) {
    var VRExperienceHelperGazer = /** @class */ (function () {
        function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
            if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
            this.scene = scene;
            /** @hidden */
            this._pointerDownOnMeshAsked = false;
            /** @hidden */
            this._isActionableMesh = false;
            /** @hidden */
            this._teleportationRequestInitiated = false;
            /** @hidden */
            this._teleportationBackRequestInitiated = false;
            /** @hidden */
            this._rotationRightAsked = false;
            /** @hidden */
            this._rotationLeftAsked = false;
            /** @hidden */
            this._dpadPressed = true;
            /** @hidden */
            this._activePointer = false;
            this._id = VRExperienceHelperGazer._idCounter++;
            // Gaze tracker
            if (!gazeTrackerToClone) {
                this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
                this._gazeTracker.bakeCurrentTransformIntoVertices();
                this._gazeTracker.isPickable = false;
                this._gazeTracker.isVisible = false;
                var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
                targetMat.specularColor = BABYLON.Color3.Black();
                targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
                targetMat.backFaceCulling = false;
                this._gazeTracker.material = targetMat;
            }
            else {
                this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
            }
        }
        /** @hidden */
        VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
            return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
        };
        /** @hidden */
        VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
            this._pointerDownOnMeshAsked = true;
            if (this._currentHit) {
                this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
            }
        };
        /** @hidden */
        VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
            if (this._currentHit) {
                this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
            }
            this._pointerDownOnMeshAsked = false;
        };
        /** @hidden */
        VRExperienceHelperGazer.prototype._activatePointer = function () {
            this._activePointer = true;
        };
        /** @hidden */
        VRExperienceHelperGazer.prototype._deactivatePointer = function () {
            this._activePointer = false;
        };
        /** @hidden */
        VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
            if (distance === void 0) { distance = 100; }
        };
        VRExperienceHelperGazer.prototype.dispose = function () {
            this._interactionsEnabled = false;
            this._teleportationEnabled = false;
            if (this._gazeTracker) {
                this._gazeTracker.dispose();
            }
        };
        VRExperienceHelperGazer._idCounter = 0;
        return VRExperienceHelperGazer;
    }());
    var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
        __extends(VRExperienceHelperControllerGazer, _super);
        function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
            var _this = _super.call(this, scene, gazeTrackerToClone) || this;
            _this.webVRController = webVRController;
            // Laser pointer
            _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
            var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
            laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
            laserPointerMaterial.alpha = 0.6;
            _this._laserPointer.material = laserPointerMaterial;
            _this._laserPointer.rotation.x = Math.PI / 2;
            _this._laserPointer.position.z = -0.5;
            _this._laserPointer.isVisible = false;
            _this._laserPointer.isPickable = false;
            if (!webVRController.mesh) {
                // Create an empty mesh that is used prior to loading the high quality model
                var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
                var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
                preloadPointerPose.rotation.x = -0.7;
                preloadMesh.addChild(preloadPointerPose);
                webVRController.attachToMesh(preloadMesh);
            }
            _this._setLaserPointerParent(webVRController.mesh);
            _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
                _this._setLaserPointerParent(mesh);
            });
            return _this;
        }
        VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
            return this.webVRController.getForwardRay(length);
        };
        /** @hidden */
        VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
            _super.prototype._activatePointer.call(this);
            this._laserPointer.isVisible = true;
        };
        /** @hidden */
        VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
            _super.prototype._deactivatePointer.call(this);
            this._laserPointer.isVisible = false;
        };
        /** @hidden */
        VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
            this._laserPointer.material.emissiveColor = color;
        };
        /** @hidden */
        VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
            var makeNotPick = function (root) {
                root.isPickable = false;
                root.getChildMeshes().forEach(function (c) {
                    makeNotPick(c);
                });
            };
            makeNotPick(mesh);
            var childMeshes = mesh.getChildMeshes();
            this.webVRController._pointingPoseNode = null;
            for (var i = 0; i < childMeshes.length; i++) {
                if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
                    mesh = childMeshes[i];
                    this.webVRController._pointingPoseNode = mesh;
                    break;
                }
            }
            this._laserPointer.parent = mesh;
        };
        VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
            if (distance === void 0) { distance = 100; }
            this._laserPointer.scaling.y = distance;
            this._laserPointer.position.z = -distance / 2;
        };
        VRExperienceHelperControllerGazer.prototype.dispose = function () {
            _super.prototype.dispose.call(this);
            this._laserPointer.dispose();
            if (this._meshAttachedObserver) {
                this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
            }
        };
        return VRExperienceHelperControllerGazer;
    }(VRExperienceHelperGazer));
    var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
        __extends(VRExperienceHelperCameraGazer, _super);
        function VRExperienceHelperCameraGazer(getCamera, scene) {
            var _this = _super.call(this, scene) || this;
            _this.getCamera = getCamera;
            return _this;
        }
        VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
            var camera = this.getCamera();
            if (camera) {
                return camera.getForwardRay(length);
            }
            else {
                return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
            }
        };
        return VRExperienceHelperCameraGazer;
    }(VRExperienceHelperGazer));
    /**
     * Helps to quickly add VR support to an existing scene.
     * See http://doc.babylonjs.com/how_to/webvr_helper
     */
    var VRExperienceHelper = /** @class */ (function () {
        /**
         * Instantiates a VRExperienceHelper.
         * Helps to quickly add VR support to an existing scene.
         * @param scene The scene the VRExperienceHelper belongs to.
         * @param webVROptions Options to modify the vr experience helper's behavior.
         */
        function VRExperienceHelper(scene, 
        /** Options to modify the vr experience helper's behavior. */
        webVROptions) {
            if (webVROptions === void 0) { webVROptions = {}; }
            var _this = this;
            this.webVROptions = webVROptions;
            // Can the system support WebVR, even if a headset isn't plugged in?
            this._webVRsupported = false;
            // If WebVR is supported, is a headset plugged in and are we ready to present?
            this._webVRready = false;
            // Are we waiting for the requestPresent callback to complete?
            this._webVRrequesting = false;
            // Are we presenting to the headset right now? (this is the vrDevice state)
            this._webVRpresenting = false;
            // Are we presenting in the fullscreen fallback?
            this._fullscreenVRpresenting = false;
            /**
             * Observable raised when entering VR.
             */
            this.onEnteringVRObservable = new BABYLON.Observable();
            /**
             * Observable raised when exiting VR.
             */
            this.onExitingVRObservable = new BABYLON.Observable();
            /**
             * Observable raised when controller mesh is loaded.
             */
            this.onControllerMeshLoadedObservable = new BABYLON.Observable();
            this._useCustomVRButton = false;
            this._teleportationRequested = false;
            this._teleportActive = false;
            this._floorMeshesCollection = [];
            this._rotationAllowed = true;
            this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
            this._isDefaultTeleportationTarget = true;
            this._teleportationFillColor = "#444444";
            this._teleportationBorderColor = "#FFFFFF";
            this._rotationAngle = 0;
            this._haloCenter = new BABYLON.Vector3(0, 0, 0);
            this._padSensibilityUp = 0.65;
            this._padSensibilityDown = 0.35;
            this._leftController = null;
            this._rightController = null;
            /**
             * Observable raised when a new mesh is selected based on meshSelectionPredicate
             */
            this.onNewMeshSelected = new BABYLON.Observable();
            /**
             * Observable raised when a new mesh is picked based on meshSelectionPredicate
             */
            this.onNewMeshPicked = new BABYLON.Observable();
            /**
             * Observable raised before camera teleportation
            */
            this.onBeforeCameraTeleport = new BABYLON.Observable();
            /**
             *  Observable raised after camera teleportation
            */
            this.onAfterCameraTeleport = new BABYLON.Observable();
            /**
            * Observable raised when current selected mesh gets unselected
            */
            this.onSelectedMeshUnselected = new BABYLON.Observable();
            /**
             * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
             */
            this.teleportationEnabled = true;
            this._teleportationInitialized = false;
            this._interactionsEnabled = false;
            this._interactionsRequested = false;
            this._displayGaze = true;
            this._displayLaserPointer = true;
            /**
             * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
             */
            this.updateGazeTrackerScale = true;
            this._onResize = function () {
                _this.moveButtonToBottomRight();
                if (_this._fullscreenVRpresenting && _this._webVRready) {
                    _this.exitVR();
                }
            };
            this._onFullscreenChange = function () {
                if (document.fullscreen !== undefined) {
                    _this._fullscreenVRpresenting = document.fullscreen;
                }
                else if (document.mozFullScreen !== undefined) {
                    _this._fullscreenVRpresenting = document.mozFullScreen;
                }
                else if (document.webkitIsFullScreen !== undefined) {
                    _this._fullscreenVRpresenting = document.webkitIsFullScreen;
                }
                else if (document.msIsFullScreen !== undefined) {
                    _this._fullscreenVRpresenting = document.msIsFullScreen;
                }
                else if (document.msFullscreenElement !== undefined) {
                    _this._fullscreenVRpresenting = document.msFullscreenElement;
                }
                if (!_this._fullscreenVRpresenting && _this._canvas) {
                    _this.exitVR();
                    if (!_this._useCustomVRButton) {
                        _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
                        _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
                    }
                }
            };
            this.beforeRender = function () {
                if (_this._leftController && _this._leftController._activePointer) {
                    _this._castRayAndSelectObject(_this._leftController);
                }
                if (_this._rightController && _this._rightController._activePointer) {
                    _this._castRayAndSelectObject(_this._rightController);
                }
                if (_this._noControllerIsActive) {
                    _this._castRayAndSelectObject(_this._cameraGazer);
                }
                else {
                    _this._cameraGazer._gazeTracker.isVisible = false;
                }
            };
            this._onNewGamepadConnected = function (gamepad) {
                if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
                    if (gamepad.leftStick) {
                        gamepad.onleftstickchanged(function (stickValues) {
                            if (_this._teleportationInitialized && _this.teleportationEnabled) {
                                // Listening to classic/xbox gamepad only if no VR controller is active
                                if ((!_this._leftController && !_this._rightController) ||
                                    ((_this._leftController && !_this._leftController._activePointer) &&
                                        (_this._rightController && !_this._rightController._activePointer))) {
                                    _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
                                    _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
                                }
                            }
                        });
                    }
                    if (gamepad.rightStick) {
                        gamepad.onrightstickchanged(function (stickValues) {
                            if (_this._teleportationInitialized) {
                                _this._checkRotate(stickValues, _this._cameraGazer);
                            }
                        });
                    }
                    if (gamepad.type === BABYLON.Gamepad.XBOX) {
                        gamepad.onbuttondown(function (buttonPressed) {
                            if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
                                _this._cameraGazer._selectionPointerDown();
                            }
                        });
                        gamepad.onbuttonup(function (buttonPressed) {
                            if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
                                _this._cameraGazer._selectionPointerUp();
                            }
                        });
                    }
                }
                else {
                    var webVRController = gamepad;
                    var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
                    if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
                        _this._rightController = controller;
                    }
                    else {
                        _this._leftController = controller;
                    }
                    _this._tryEnableInteractionOnController(controller);
                }
            };
            // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
            this._tryEnableInteractionOnController = function (controller) {
                if (_this._interactionsRequested && !controller._interactionsEnabled) {
                    _this._enableInteractionOnController(controller);
                }
                if (_this._teleportationRequested && !controller._teleportationEnabled) {
                    _this._enableTeleportationOnController(controller);
                }
            };
            this._onNewGamepadDisconnected = function (gamepad) {
                if (gamepad instanceof BABYLON.WebVRController) {
                    if (gamepad.hand === "left" && _this._leftController != null) {
                        _this._leftController.dispose();
                        _this._leftController = null;
                    }
                    if (gamepad.hand === "right" && _this._rightController != null) {
                        _this._rightController.dispose();
                        _this._rightController = null;
                    }
                }
            };
            this._workingVector = BABYLON.Vector3.Zero();
            this._workingQuaternion = BABYLON.Quaternion.Identity();
            this._workingMatrix = BABYLON.Matrix.Identity();
            this._scene = scene;
            this._canvas = scene.getEngine().getRenderingCanvas();
            // Parse options
            if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
                webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
            }
            if (webVROptions.createDeviceOrientationCamera === undefined) {
                webVROptions.createDeviceOrientationCamera = true;
            }
            if (webVROptions.laserToggle === undefined) {
                webVROptions.laserToggle = true;
            }
            if (webVROptions.defaultHeight === undefined) {
                webVROptions.defaultHeight = 1.7;
            }
            if (webVROptions.useCustomVRButton) {
                this._useCustomVRButton = true;
                if (webVROptions.customVRButton) {
                    this._btnVR = webVROptions.customVRButton;
                }
            }
            if (webVROptions.rayLength) {
                this._rayLength = webVROptions.rayLength;
            }
            this._defaultHeight = webVROptions.defaultHeight;
            if (webVROptions.positionScale) {
                this._rayLength *= webVROptions.positionScale;
                this._defaultHeight *= webVROptions.positionScale;
            }
            this._hasEnteredVR = false;
            // Set position
            if (this._scene.activeCamera) {
                this._position = this._scene.activeCamera.position.clone();
            }
            else {
                this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
            }
            // Set non-vr camera
            if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
                this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
                // Copy data from existing camera
                if (this._scene.activeCamera) {
                    this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
                    this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
                    // Set rotation from previous camera
                    if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
                        var targetCamera = this._scene.activeCamera;
                        if (targetCamera.rotationQuaternion) {
                            this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
                        }
                        else {
                            this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
                        }
                        this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
                    }
                }
                this._scene.activeCamera = this._deviceOrientationCamera;
                if (this._canvas) {
                    this._scene.activeCamera.attachControl(this._canvas);
                }
            }
            else {
                this._existingCamera = this._scene.activeCamera;
            }
            // Create VR cameras
            if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
                this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
            }
            this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
            this._webVRCamera.useStandingMatrix();
            this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
            // Create default button
            if (!this._useCustomVRButton) {
                this._btnVR = document.createElement("BUTTON");
                this._btnVR.className = "babylonVRicon";
                this._btnVR.id = "babylonVRiconbtn";
                this._btnVR.title = "Click to switch to VR";
                var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
                css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
                // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
                // css += ".babylonVRicon.vrdisplaysupported { }";
                // css += ".babylonVRicon.vrdisplayready { }";
                // css += ".babylonVRicon.vrdisplayrequesting { }";
                var style = document.createElement('style');
                style.appendChild(document.createTextNode(css));
                document.getElementsByTagName('head')[0].appendChild(style);
                this.moveButtonToBottomRight();
            }
            // VR button click event
            if (this._btnVR) {
                this._btnVR.addEventListener("click", function () {
                    if (!_this.isInVRMode) {
                        _this.enterVR();
                    }
                    else {
                        _this.exitVR();
                    }
                });
            }
            // Window events
            window.addEventListener("resize", this._onResize);
            document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
            document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
            document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
            document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
            document.onmsfullscreenchange = this._onFullscreenChange;
            // Display vr button when headset is connected
            if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
                this.displayVRButton();
            }
            else {
                this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
                    if (e.vrDisplay) {
                        _this.displayVRButton();
                    }
                });
            }
            // Exiting VR mode using 'ESC' key on desktop
            this._onKeyDown = function (event) {
                if (event.keyCode === 27 && _this.isInVRMode) {
                    _this.exitVR();
                }
            };
            document.addEventListener("keydown", this._onKeyDown);
            // Exiting VR mode double tapping the touch screen
            this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
                if (_this.isInVRMode) {
                    _this.exitVR();
                    if (_this._fullscreenVRpresenting) {
                        _this._scene.getEngine().switchFullscreen(true);
                    }
                }
            }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
            // Listen for WebVR display changes
            this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
            this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
            this._onVRRequestPresentStart = function () {
                _this._webVRrequesting = true;
                _this.updateButtonVisibility();
            };
            this._onVRRequestPresentComplete = function (success) {
                _this._webVRrequesting = false;
                _this.updateButtonVisibility();
            };
            scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
            scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
            scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
            window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
            scene.onDisposeObservable.add(function () {
                _this.dispose();
            });
            // Gamepad connection events
            this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
            this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
            this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
            this.updateButtonVisibility();
            //create easing functions
            this._circleEase = new BABYLON.CircleEase();
            this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
            if (this.webVROptions.floorMeshes) {
                this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
            }
        }
        Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
            /** Return this.onEnteringVRObservable
             * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
             */
            get: function () {
                return this.onEnteringVRObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
            /** Return this.onExitingVRObservable
             * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
             */
            get: function () {
                return this.onExitingVRObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
            /** Return this.onControllerMeshLoadedObservable
             * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
             */
            get: function () {
                return this.onControllerMeshLoadedObservable;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
            /**
             * The mesh used to display where the user is going to teleport.
             */
            get: function () {
                return this._teleportationTarget;
            },
            /**
             * Sets the mesh to be used to display where the user is going to teleport.
             */
            set: function (value) {
                if (value) {
                    value.name = "teleportationTarget";
                    this._isDefaultTeleportationTarget = false;
                    this._teleportationTarget = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
            /**
             * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller
             * when set bakeCurrentTransformIntoVertices will be called on the mesh.
             * See http://doc.babylonjs.com/resources/baking_transformations
             */
            get: function () {
                return this._cameraGazer._gazeTracker;
            },
            set: function (value) {
                if (value) {
                    // Dispose of existing meshes
                    if (this._cameraGazer._gazeTracker) {
                        this._cameraGazer._gazeTracker.dispose();
                    }
                    if (this._leftController && this._leftController._gazeTracker) {
                        this._leftController._gazeTracker.dispose();
                    }
                    if (this._rightController && this._rightController._gazeTracker) {
                        this._rightController._gazeTracker.dispose();
                    }
                    // Set and create gaze trackers on head and controllers
                    this._cameraGazer._gazeTracker = value;
                    this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
                    this._cameraGazer._gazeTracker.isPickable = false;
                    this._cameraGazer._gazeTracker.isVisible = false;
                    this._cameraGazer._gazeTracker.name = "gazeTracker";
                    if (this._leftController) {
                        this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
                    }
                    if (this._rightController) {
                        this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
            /**
             * The gaze tracking mesh corresponding to the left controller
             */
            get: function () {
                if (this._leftController) {
                    return this._leftController._gazeTracker;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
            /**
             * The gaze tracking mesh corresponding to the right controller
             */
            get: function () {
                if (this._rightController) {
                    return this._rightController._gazeTracker;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
            /**
             * If the ray of the gaze should be displayed.
             */
            get: function () {
                return this._displayGaze;
            },
            /**
             * Sets if the ray of the gaze should be displayed.
             */
            set: function (value) {
                this._displayGaze = value;
                if (!value) {
                    this._cameraGazer._gazeTracker.isVisible = false;
                    if (this._leftController) {
                        this._leftController._gazeTracker.isVisible = false;
                    }
                    if (this._rightController) {
                        this._rightController._gazeTracker.isVisible = false;
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
            /**
             * If the ray of the LaserPointer should be displayed.
             */
            get: function () {
                return this._displayLaserPointer;
            },
            /**
             * Sets if the ray of the LaserPointer should be displayed.
             */
            set: function (value) {
                this._displayLaserPointer = value;
                if (!value) {
                    if (this._rightController) {
                        this._rightController._deactivatePointer();
                        this._rightController._gazeTracker.isVisible = false;
                    }
                    if (this._leftController) {
                        this._leftController._deactivatePointer();
                        this._leftController._gazeTracker.isVisible = false;
                    }
                }
                else {
                    if (this._rightController) {
                        this._rightController._activatePointer();
                    }
                    if (this._leftController) {
                        this._leftController._activatePointer();
                    }
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
            /**
             * The deviceOrientationCamera used as the camera when not in VR.
             */
            get: function () {
                return this._deviceOrientationCamera;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
            /**
             * Based on the current WebVR support, returns the current VR camera used.
             */
            get: function () {
                if (this._webVRready) {
                    return this._webVRCamera;
                }
                else {
                    return this._scene.activeCamera;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
            /**
             * The webVRCamera which is used when in VR.
             */
            get: function () {
                return this._webVRCamera;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
            /**
             * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
             */
            get: function () {
                return this._vrDeviceOrientationCamera;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
            get: function () {
                var result = this._cameraGazer._teleportationRequestInitiated
                    || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
                    || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
                return result;
            },
            enumerable: true,
            configurable: true
        });
        // Raised when one of the controller has loaded successfully its associated default mesh
        VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
            if (this._leftController && this._leftController.webVRController == webVRController) {
                if (webVRController.mesh) {
                    this._leftController._setLaserPointerParent(webVRController.mesh);
                }
            }
            if (this._rightController && this._rightController.webVRController == webVRController) {
                if (webVRController.mesh) {
                    this._rightController._setLaserPointerParent(webVRController.mesh);
                }
            }
            try {
                this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
            }
            catch (err) {
                BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
            }
        };
        Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
            /**
             * Gets a value indicating if we are currently in VR mode.
             */
            get: function () {
                return this._webVRpresenting || this._fullscreenVRpresenting;
            },
            enumerable: true,
            configurable: true
        });
        VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
            var vrDisplay = this._scene.getEngine().getVRDevice();
            if (vrDisplay) {
                var wasPresenting = this._webVRpresenting;
                this._webVRpresenting = vrDisplay.isPresenting;
                if (wasPresenting && !this._webVRpresenting) {
                    this.exitVR();
                }
            }
            else {
                BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
            }
            this.updateButtonVisibility();
        };
        VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
            this._webVRsupported = eventArgs.vrSupported;
            this._webVRready = !!eventArgs.vrDisplay;
            this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
            this.updateButtonVisibility();
        };
        VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
            if (this._canvas && !this._useCustomVRButton) {
                this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
                this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
            }
        };
        VRExperienceHelper.prototype.displayVRButton = function () {
            if (!this._useCustomVRButton && !this._btnVRDisplayed) {
                document.body.appendChild(this._btnVR);
                this._btnVRDisplayed = true;
            }
        };
        VRExperienceHelper.prototype.updateButtonVisibility = function () {
            if (!this._btnVR || this._useCustomVRButton) {
                return;
            }
            this._btnVR.className = "babylonVRicon";
            if (this.isInVRMode) {
                this._btnVR.className += " vrdisplaypresenting";
            }
            else {
                if (this._webVRready) {
                    this._btnVR.className += " vrdisplayready";
                }
                if (this._webVRsupported) {
                    this._btnVR.className += " vrdisplaysupported";
                }
                if (this._webVRrequesting) {
                    this._btnVR.className += " vrdisplayrequesting";
                }
            }
        };
        /**
         * Attempt to enter VR. If a headset is connected and ready, will request present on that.
         * Otherwise, will use the fullscreen API.
         */
        VRExperienceHelper.prototype.enterVR = function () {
            if (this.onEnteringVRObservable) {
                try {
                    this.onEnteringVRObservable.notifyObservers(this);
                }
                catch (err) {
                    BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
                }
            }
            if (this._scene.activeCamera) {
                this._position = this._scene.activeCamera.position.clone();
                // make sure that we return to the last active camera
                this._existingCamera = this._scene.activeCamera;
            }
            if (this._webVRrequesting) {
                return;
            }
            // If WebVR is supported and a headset is connected
            if (this._webVRready) {
                if (!this._webVRpresenting) {
                    this._webVRCamera.position = this._position;
                    this._scene.activeCamera = this._webVRCamera;
                }
            }
            else if (this._vrDeviceOrientationCamera) {
                this._vrDeviceOrientationCamera.position = this._position;
                if (this._scene.activeCamera) {
                    this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
                }
                this._scene.activeCamera = this._vrDeviceOrientationCamera;
                this._scene.getEngine().switchFullscreen(true);
                this.updateButtonVisibility();
            }
            if (this._scene.activeCamera && this._canvas) {
                this._scene.activeCamera.attachControl(this._canvas);
            }
            if (this._interactionsEnabled) {
                this._scene.registerBeforeRender(this.beforeRender);
            }
            this._hasEnteredVR = true;
        };
        /**
         * Attempt to exit VR, or fullscreen.
         */
        VRExperienceHelper.prototype.exitVR = function () {
            if (this._hasEnteredVR) {
                if (this.onExitingVRObservable) {
                    try {
                        this.onExitingVRObservable.notifyObservers(this);
                    }
                    catch (err) {
                        BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
                    }
                }
                if (this._webVRpresenting) {
                    this._scene.getEngine().disableVR();
                }
                if (this._scene.activeCamera) {
                    this._position = this._scene.activeCamera.position.clone();
                }
                if (this._deviceOrientationCamera) {
                    this._deviceOrientationCamera.position = this._position;
                    this._scene.activeCamera = this._deviceOrientationCamera;
                    if (this._canvas) {
                        this._scene.activeCamera.attachControl(this._canvas);
                    }
                }
                else if (this._existingCamera) {
                    this._existingCamera.position = this._position;
                    this._scene.activeCamera = this._existingCamera;
                }
                this.updateButtonVisibility();
                if (this._interactionsEnabled) {
                    this._scene.unregisterBeforeRender(this.beforeRender);
                    this._cameraGazer._gazeTracker.isVisible = false;
                    if (this._leftController) {
                        this._leftController._gazeTracker.isVisible = false;
                    }
                    if (this._rightController) {
                        this._rightController._gazeTracker.isVisible = false;
                    }
                }
                // resize to update width and height when exiting vr exits fullscreen
                this._scene.getEngine().resize();
                this._hasEnteredVR = false;
            }
        };
        Object.defineProperty(VRExperienceHelper.prototype, "position", {
            /**
             * The position of the vr experience helper.
             */
            get: function () {
                return this._position;
            },
            /**
             * Sets the position of the vr experience helper.
             */
            set: function (value) {
                this._position = value;
                if (this._scene.activeCamera) {
                    this._scene.activeCamera.position = value;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Enables controllers and user interactions such as selecting and object or clicking on an object.
         */
        VRExperienceHelper.prototype.enableInteractions = function () {
            var _this = this;
            if (!this._interactionsEnabled) {
                this._interactionsRequested = true;
                if (this._leftController) {
                    this._enableInteractionOnController(this._leftController);
                }
                if (this._rightController) {
                    this._enableInteractionOnController(this._rightController);
                }
                this.raySelectionPredicate = function (mesh) {
                    return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
                };
                this.meshSelectionPredicate = function (mesh) {
                    return true;
                };
                this._raySelectionPredicate = function (mesh) {
                    if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
                        && mesh.name.indexOf("teleportationTarget") === -1
                        && mesh.name.indexOf("torusTeleportation") === -1)) {
                        return _this.raySelectionPredicate(mesh);
                    }
                    return false;
                };
                this._interactionsEnabled = true;
            }
        };
        Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
            get: function () {
                return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
            },
            enumerable: true,
            configurable: true
        });
        VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
            for (var i = 0; i < this._floorMeshesCollection.length; i++) {
                if (this._floorMeshesCollection[i].id === mesh.id) {
                    return true;
                }
            }
            if (this._floorMeshName && mesh.name === this._floorMeshName) {
                return true;
            }
            return false;
        };
        /**
         * Adds a floor mesh to be used for teleportation.
         * @param floorMesh the mesh to be used for teleportation.
         */
        VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
            if (!this._floorMeshesCollection) {
                return;
            }
            if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
                return;
            }
            this._floorMeshesCollection.push(floorMesh);
        };
        /**
         * Removes a floor mesh from being used for teleportation.
         * @param floorMesh the mesh to be removed.
         */
        VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
            if (!this._floorMeshesCollection) {
                return;
            }
            var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
            if (meshIndex !== -1) {
                this._floorMeshesCollection.splice(meshIndex, 1);
            }
        };
        /**
         * Enables interactions and teleportation using the VR controllers and gaze.
         * @param vrTeleportationOptions options to modify teleportation behavior.
         */
        VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
            if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
            if (!this._teleportationInitialized) {
                this._teleportationRequested = true;
                this.enableInteractions();
                if (vrTeleportationOptions.floorMeshName) {
                    this._floorMeshName = vrTeleportationOptions.floorMeshName;
                }
                if (vrTeleportationOptions.floorMeshes) {
                    this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
                }
                if (this._leftController != null) {
                    this._enableTeleportationOnController(this._leftController);
                }
                if (this._rightController != null) {
                    this._enableTeleportationOnController(this._rightController);
                }
                // Creates an image processing post process for the vignette not relying
                // on the main scene configuration for image processing to reduce setup and spaces
                // (gamma/linear) conflicts.
                var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
                imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
                imageProcessingConfiguration.vignetteEnabled = true;
                this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
                this._webVRCamera.detachPostProcess(this._postProcessMove);
                this._teleportationInitialized = true;
                if (this._isDefaultTeleportationTarget) {
                    this._createTeleportationCircles();
                    this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
                }
            }
        };
        VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
            var _this = this;
            var controllerMesh = controller.webVRController.mesh;
            if (controllerMesh) {
                controller._interactionsEnabled = true;
                controller._activatePointer();
                if (this.webVROptions.laserToggle) {
                    controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
                        // Enabling / disabling laserPointer
                        if (_this._displayLaserPointer && stateObject.value === 1) {
                            if (controller._activePointer) {
                                controller._deactivatePointer();
                            }
                            else {
                                controller._activatePointer();
                            }
                            if (_this.displayGaze) {
                                controller._gazeTracker.isVisible = controller._activePointer;
                            }
                        }
                    });
                }
                controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
                    var gazer = controller;
                    if (_this._noControllerIsActive) {
                        gazer = _this._cameraGazer;
                    }
                    if (!gazer._pointerDownOnMeshAsked) {
                        if (stateObject.value > _this._padSensibilityUp) {
                            gazer._selectionPointerDown();
                        }
                    }
                    else if (stateObject.value < _this._padSensibilityDown) {
                        gazer._selectionPointerUp();
                    }
                });
            }
        };
        VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
            // Dont teleport if another gaze already requested teleportation
            if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
                return;
            }
            if (!gazer._teleportationRequestInitiated) {
                if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
                    gazer._activatePointer();
                    gazer._teleportationRequestInitiated = true;
                }
            }
            else {
                // Listening to the proper controller values changes to confirm teleportation
                if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
                    if (this._teleportActive) {
                        this.teleportCamera(this._haloCenter);
                    }
                    gazer._teleportationRequestInitiated = false;
                }
            }
        };
        VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
            // Only rotate when user is not currently selecting a teleportation location
            if (gazer._teleportationRequestInitiated) {
                return;
            }
            if (!gazer._rotationLeftAsked) {
                if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
                    gazer._rotationLeftAsked = true;
                    if (this._rotationAllowed) {
                        this._rotateCamera(false);
                    }
                }
            }
            else {
                if (stateObject.x > -this._padSensibilityDown) {
                    gazer._rotationLeftAsked = false;
                }
            }
            if (!gazer._rotationRightAsked) {
                if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
                    gazer._rotationRightAsked = true;
                    if (this._rotationAllowed) {
                        this._rotateCamera(true);
                    }
                }
            }
            else {
                if (stateObject.x < this._padSensibilityDown) {
                    gazer._rotationRightAsked = false;
                }
            }
        };
        VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
            // Only teleport backwards when user is not currently selecting a teleportation location
            if (gazer._teleportationRequestInitiated) {
                return;
            }
            // Teleport backwards
            if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
                if (!gazer._teleportationBackRequestInitiated) {
                    if (!this.currentVRCamera) {
                        return;
                    }
                    // Get rotation and position of the current camera
                    var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
                    var position = this.currentVRCamera.position;
                    // If the camera has device position, use that instead
                    if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
                        rotation = this.currentVRCamera.deviceRotationQuaternion;
                        position = this.currentVRCamera.devicePosition;
                    }
                    // Get matrix with only the y rotation of the device rotation
                    rotation.toEulerAnglesToRef(this._workingVector);
                    this._workingVector.z = 0;
                    this._workingVector.x = 0;
                    BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
                    this._workingQuaternion.toRotationMatrix(this._workingMatrix);
                    // Rotate backwards ray by device rotation to cast at the ground behind the user
                    BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
                    // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
                    var ray = new BABYLON.Ray(position, this._workingVector);
                    var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
                    if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
                        this.teleportCamera(hit.pickedPoint);
                    }
                    gazer._teleportationBackRequestInitiated = true;
                }
            }
            else {
                gazer._teleportationBackRequestInitiated = false;
            }
        };
        VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
            var _this = this;
            var controllerMesh = controller.webVRController.mesh;
            if (controllerMesh) {
                if (!controller._interactionsEnabled) {
                    this._enableInteractionOnController(controller);
                }
                controller._interactionsEnabled = true;
                controller._teleportationEnabled = true;
                if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
                    controller._dpadPressed = false;
                    controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
                        controller._dpadPressed = stateObject.pressed;
                        if (!controller._dpadPressed) {
                            controller._rotationLeftAsked = false;
                            controller._rotationRightAsked = false;
                            controller._teleportationBackRequestInitiated = false;
                        }
                    });
                }
                controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
                    if (_this.teleportationEnabled) {
                        _this._checkTeleportBackwards(stateObject, controller);
                        _this._checkTeleportWithRay(stateObject, controller);
                    }
                    _this._checkRotate(stateObject, controller);
                });
            }
        };
        VRExperienceHelper.prototype._createTeleportationCircles = function () {
            this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
            this._teleportationTarget.isPickable = false;
            var length = 512;
            var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
            dynamicTexture.hasAlpha = true;
            var context = dynamicTexture.getContext();
            var centerX = length / 2;
            var centerY = length / 2;
            var radius = 200;
            context.beginPath();
            context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
            context.fillStyle = this._teleportationFillColor;
            context.fill();
            context.lineWidth = 10;
            context.strokeStyle = this._teleportationBorderColor;
            context.stroke();
            context.closePath();
            dynamicTexture.update();
            var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
            teleportationCircleMaterial.diffuseTexture = dynamicTexture;
            this._teleportationTarget.material = teleportationCircleMaterial;
            var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
            torus.isPickable = false;
            torus.parent = this._teleportationTarget;
            var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
            var keys = [];
            keys.push({
                frame: 0,
                value: 0
            });
            keys.push({
                frame: 30,
                value: 0.4
            });
            keys.push({
                frame: 60,
                value: 0
            });
            animationInnerCircle.setKeys(keys);
            var easingFunction = new BABYLON.SineEase();
            easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
            animationInnerCircle.setEasingFunction(easingFunction);
            torus.animations = [];
            torus.animations.push(animationInnerCircle);
            this._scene.beginAnimation(torus, 0, 60, true);
            this._hideTeleportationTarget();
        };
        VRExperienceHelper.prototype._displayTeleportationTarget = function () {
            this._teleportActive = true;
            if (this._teleportationInitialized) {
                this._teleportationTarget.isVisible = true;
                if (this._isDefaultTeleportationTarget) {
                    this._teleportationTarget.getChildren()[0].isVisible = true;
                }
            }
        };
        VRExperienceHelper.prototype._hideTeleportationTarget = function () {
            this._teleportActive = false;
            if (this._teleportationInitialized) {
                this._teleportationTarget.isVisible = false;
                if (this._isDefaultTeleportationTarget) {
                    this._teleportationTarget.getChildren()[0].isVisible = false;
                }
            }
        };
        VRExperienceHelper.prototype._rotateCamera = function (right) {
            var _this = this;
            if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
                return;
            }
            if (right) {
                this._rotationAngle++;
            }
            else {
                this._rotationAngle--;
            }
            this.currentVRCamera.animations = [];
            var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
            var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            var animationRotationKeys = [];
            animationRotationKeys.push({
                frame: 0,
                value: this.currentVRCamera.rotationQuaternion
            });
            animationRotationKeys.push({
                frame: 6,
                value: target
            });
            animationRotation.setKeys(animationRotationKeys);
            animationRotation.setEasingFunction(this._circleEase);
            this.currentVRCamera.animations.push(animationRotation);
            this._postProcessMove.animations = [];
            var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            var vignetteWeightKeys = [];
            vignetteWeightKeys.push({
                frame: 0,
                value: 0
            });
            vignetteWeightKeys.push({
                frame: 3,
                value: 4
            });
            vignetteWeightKeys.push({
                frame: 6,
                value: 0
            });
            animationPP.setKeys(vignetteWeightKeys);
            animationPP.setEasingFunction(this._circleEase);
            this._postProcessMove.animations.push(animationPP);
            var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            var vignetteStretchKeys = [];
            vignetteStretchKeys.push({
                frame: 0,
                value: 0
            });
            vignetteStretchKeys.push({
                frame: 3,
                value: 10
            });
            vignetteStretchKeys.push({
                frame: 6,
                value: 0
            });
            animationPP2.setKeys(vignetteStretchKeys);
            animationPP2.setEasingFunction(this._circleEase);
            this._postProcessMove.animations.push(animationPP2);
            this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
            this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
            this._postProcessMove.samples = 4;
            this._webVRCamera.attachPostProcess(this._postProcessMove);
            this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
                _this._webVRCamera.detachPostProcess(_this._postProcessMove);
            });
            this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
        };
        VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
            if (hit.pickedPoint) {
                if (gazer._teleportationRequestInitiated) {
                    this._displayTeleportationTarget();
                    this._haloCenter.copyFrom(hit.pickedPoint);
                    this._teleportationTarget.position.copyFrom(hit.pickedPoint);
                }
                var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
                if (pickNormal) {
                    var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
                    var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
                    BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
                }
                this._teleportationTarget.position.y += 0.1;
            }
        };
        /**
         * Teleports the users feet to the desired location
         * @param location The location where the user's feet should be placed
         */
        VRExperienceHelper.prototype.teleportCamera = function (location) {
            var _this = this;
            if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
                return;
            }
            // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
            // offset of the headset from the anchor.
            if (this.webVRCamera.leftCamera) {
                this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
                this._workingVector.subtractInPlace(this.webVRCamera.position);
                location.subtractToRef(this._workingVector, this._workingVector);
            }
            else {
                this._workingVector.copyFrom(location);
            }
            // Add height to account for user's height offset
            if (this.isInVRMode) {
                this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
            }
            else {
                this._workingVector.y += this._defaultHeight;
            }
            this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
            // Create animation from the camera's position to the new location
            this.currentVRCamera.animations = [];
            var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            var animationCameraTeleportationKeys = [{
                    frame: 0,
                    value: this.currentVRCamera.position
                },
                {
                    frame: 11,
                    value: this._workingVector
                }
            ];
            animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
            animationCameraTeleportation.setEasingFunction(this._circleEase);
            this.currentVRCamera.animations.push(animationCameraTeleportation);
            this._postProcessMove.animations = [];
            var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            var vignetteWeightKeys = [];
            vignetteWeightKeys.push({
                frame: 0,
                value: 0
            });
            vignetteWeightKeys.push({
                frame: 5,
                value: 8
            });
            vignetteWeightKeys.push({
                frame: 11,
                value: 0
            });
            animationPP.setKeys(vignetteWeightKeys);
            this._postProcessMove.animations.push(animationPP);
            var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
            var vignetteStretchKeys = [];
            vignetteStretchKeys.push({
                frame: 0,
                value: 0
            });
            vignetteStretchKeys.push({
                frame: 5,
                value: 10
            });
            vignetteStretchKeys.push({
                frame: 11,
                value: 0
            });
            animationPP2.setKeys(vignetteStretchKeys);
            this._postProcessMove.animations.push(animationPP2);
            this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
            this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
            this._webVRCamera.attachPostProcess(this._postProcessMove);
            this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
                _this._webVRCamera.detachPostProcess(_this._postProcessMove);
            });
            this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
                _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
            });
            this._hideTeleportationTarget();
        };
        VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
            if (normal) {
                var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
                if (angle < Math.PI / 2) {
                    normal.scaleInPlace(-1);
                }
            }
            return normal;
        };
        VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
            if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
                return;
            }
            var ray = gazer._getForwardRay(this._rayLength);
            var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
            if (hit) {
                // Populate the contrllers mesh that can be used for drag/drop
                if (gazer._laserPointer) {
                    hit.originMesh = gazer._laserPointer.parent;
                }
                this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
            }
            gazer._currentHit = hit;
            // Moving the gazeTracker on the mesh face targetted
            if (hit && hit.pickedPoint) {
                if (this._displayGaze) {
                    var multiplier = 1;
                    gazer._gazeTracker.isVisible = true;
                    if (gazer._isActionableMesh) {
                        multiplier = 3;
                    }
                    if (this.updateGazeTrackerScale) {
                        gazer._gazeTracker.scaling.x = hit.distance * multiplier;
                        gazer._gazeTracker.scaling.y = hit.distance * multiplier;
                        gazer._gazeTracker.scaling.z = hit.distance * multiplier;
                    }
                    var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
                    // To avoid z-fighting
                    var deltaFighting = 0.002;
                    if (pickNormal) {
                        var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
                        var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
                        BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
                    }
                    gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
                    if (gazer._gazeTracker.position.x < 0) {
                        gazer._gazeTracker.position.x += deltaFighting;
                    }
                    else {
                        gazer._gazeTracker.position.x -= deltaFighting;
                    }
                    if (gazer._gazeTracker.position.y < 0) {
                        gazer._gazeTracker.position.y += deltaFighting;
                    }
                    else {
                        gazer._gazeTracker.position.y -= deltaFighting;
                    }
                    if (gazer._gazeTracker.position.z < 0) {
                        gazer._gazeTracker.position.z += deltaFighting;
                    }
                    else {
                        gazer._gazeTracker.position.z -= deltaFighting;
                    }
                }
                // Changing the size of the laser pointer based on the distance from the targetted point
                gazer._updatePointerDistance(hit.distance);
            }
            else {
                gazer._updatePointerDistance();
                gazer._gazeTracker.isVisible = false;
            }
            if (hit && hit.pickedMesh) {
                // The object selected is the floor, we're in a teleportation scenario
                if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
                    // Moving the teleportation area to this targetted point
                    //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
                    if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
                        this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
                    }
                    gazer._currentMeshSelected = null;
                    if (gazer._teleportationRequestInitiated) {
                        this._moveTeleportationSelectorTo(hit, gazer, ray);
                    }
                    return;
                }
                // If not, we're in a selection scenario
                //this._teleportationAllowed = false;
                if (hit.pickedMesh !== gazer._currentMeshSelected) {
                    if (this.meshSelectionPredicate(hit.pickedMesh)) {
                        this.onNewMeshPicked.notifyObservers(hit);
                        gazer._currentMeshSelected = hit.pickedMesh;
                        if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
                            this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
                            this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
                            gazer._isActionableMesh = true;
                        }
                        else {
                            this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
                            this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
                            gazer._isActionableMesh = false;
                        }
                        try {
                            this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
                        }
                        catch (err) {
                            BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
                        }
                    }
                    else {
                        this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
                        gazer._currentMeshSelected = null;
                        this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
                        this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
                    }
                }
            }
            else {
                this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
                gazer._currentMeshSelected = null;
                //this._teleportationAllowed = false;
                this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
                this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
            }
        };
        VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
            if (mesh) {
                this.onSelectedMeshUnselected.notifyObservers(mesh);
            }
        };
        /**
         * Sets the color of the laser ray from the vr controllers.
         * @param color new color for the ray.
         */
        VRExperienceHelper.prototype.changeLaserColor = function (color) {
            if (this._leftController) {
                this._leftController._setLaserPointerColor(color);
            }
            if (this._rightController) {
                this._rightController._setLaserPointerColor(color);
            }
        };
        /**
         * Sets the color of the ray from the vr headsets gaze.
         * @param color new color for the ray.
         */
        VRExperienceHelper.prototype.changeGazeColor = function (color) {
            if (!this._cameraGazer._gazeTracker.material) {
                return;
            }
            this._cameraGazer._gazeTracker.material.emissiveColor = color;
            if (this._leftController) {
                this._leftController._gazeTracker.material.emissiveColor = color;
            }
            if (this._rightController) {
                this._rightController._gazeTracker.material.emissiveColor = color;
            }
        };
        /**
         * Exits VR and disposes of the vr experience helper
         */
        VRExperienceHelper.prototype.dispose = function () {
            if (this.isInVRMode) {
                this.exitVR();
            }
            if (this._postProcessMove) {
                this._postProcessMove.dispose();
            }
            if (this._webVRCamera) {
                this._webVRCamera.dispose();
            }
            if (this._vrDeviceOrientationCamera) {
                this._vrDeviceOrientationCamera.dispose();
            }
            if (!this._useCustomVRButton && this._btnVR.parentNode) {
                document.body.removeChild(this._btnVR);
            }
            if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
                this._deviceOrientationCamera.dispose();
            }
            if (this._cameraGazer) {
                this._cameraGazer.dispose();
            }
            if (this._leftController) {
                this._leftController.dispose();
            }
            if (this._rightController) {
                this._rightController.dispose();
            }
            if (this._teleportationTarget) {
                this._teleportationTarget.dispose();
            }
            this._floorMeshesCollection = [];
            document.removeEventListener("keydown", this._onKeyDown);
            window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
            window.removeEventListener("resize", this._onResize);
            document.removeEventListener("fullscreenchange", this._onFullscreenChange);
            document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
            document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
            document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
            document.onmsfullscreenchange = null;
            this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
            this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
            this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
            window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
            this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
            this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
            this._scene.unregisterBeforeRender(this.beforeRender);
        };
        /**
         * Gets the name of the VRExperienceHelper class
         * @returns "VRExperienceHelper"
         */
        VRExperienceHelper.prototype.getClassName = function () {
            return "VRExperienceHelper";
        };
        return VRExperienceHelper;
    }());
    BABYLON.VRExperienceHelper = VRExperienceHelper;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.vrExperienceHelper.js.map

// Mainly based on these 2 articles :
// Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
// & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
var BABYLON;
(function (BABYLON) {
    /**
     * Defines the potential axis of a Joystick
     */
    var JoystickAxis;
    (function (JoystickAxis) {
        /** X axis */
        JoystickAxis[JoystickAxis["X"] = 0] = "X";
        /** Y axis */
        JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
        /** Z axis */
        JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
    })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
    /**
     * Class used to define virtual joystick (used in touch mode)
     */
    var VirtualJoystick = /** @class */ (function () {
        /**
         * Creates a new virtual joystick
         * @param leftJoystick defines that the joystick is for left hand (false by default)
         */
        function VirtualJoystick(leftJoystick) {
            var _this = this;
            if (leftJoystick) {
                this._leftJoystick = true;
            }
            else {
                this._leftJoystick = false;
            }
            VirtualJoystick._globalJoystickIndex++;
            // By default left & right arrow keys are moving the X
            // and up & down keys are moving the Y
            this._axisTargetedByLeftAndRight = JoystickAxis.X;
            this._axisTargetedByUpAndDown = JoystickAxis.Y;
            this.reverseLeftRight = false;
            this.reverseUpDown = false;
            // collections of pointers
            this._touches = new BABYLON.StringDictionary();
            this.deltaPosition = BABYLON.Vector3.Zero();
            this._joystickSensibility = 25;
            this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
            this._onResize = function (evt) {
                VirtualJoystick.vjCanvasWidth = window.innerWidth;
                VirtualJoystick.vjCanvasHeight = window.innerHeight;
                if (VirtualJoystick.vjCanvas) {
                    VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
                    VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
                }
                VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
            };
            // injecting a canvas element on top of the canvas 3D game
            if (!VirtualJoystick.vjCanvas) {
                window.addEventListener("resize", this._onResize, false);
                VirtualJoystick.vjCanvas = document.createElement("canvas");
                VirtualJoystick.vjCanvasWidth = window.innerWidth;
                VirtualJoystick.vjCanvasHeight = window.innerHeight;
                VirtualJoystick.vjCanvas.width = window.innerWidth;
                VirtualJoystick.vjCanvas.height = window.innerHeight;
                VirtualJoystick.vjCanvas.style.width = "100%";
                VirtualJoystick.vjCanvas.style.height = "100%";
                VirtualJoystick.vjCanvas.style.position = "absolute";
                VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
                VirtualJoystick.vjCanvas.style.top = "0px";
                VirtualJoystick.vjCanvas.style.left = "0px";
                VirtualJoystick.vjCanvas.style.zIndex = "5";
                VirtualJoystick.vjCanvas.style.msTouchAction = "none";
                // Support for jQuery PEP polyfill
                VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
                var context = VirtualJoystick.vjCanvas.getContext('2d');
                if (!context) {
                    throw new Error("Unable to create canvas for virtual joystick");
                }
                VirtualJoystick.vjCanvasContext = context;
                VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
                VirtualJoystick.vjCanvasContext.lineWidth = 2;
                document.body.appendChild(VirtualJoystick.vjCanvas);
            }
            VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
            this.pressed = false;
            // default joystick color
            this._joystickColor = "cyan";
            this._joystickPointerID = -1;
            // current joystick position
            this._joystickPointerPos = new BABYLON.Vector2(0, 0);
            this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
            // origin joystick position
            this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
            this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
            this._onPointerDownHandlerRef = function (evt) {
                _this._onPointerDown(evt);
            };
            this._onPointerMoveHandlerRef = function (evt) {
                _this._onPointerMove(evt);
            };
            this._onPointerUpHandlerRef = function (evt) {
                _this._onPointerUp(evt);
            };
            VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
            VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
                evt.preventDefault(); // Disables system menu
            }, false);
            requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
        }
        /**
         * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
         * @param newJoystickSensibility defines the new sensibility
         */
        VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
            this._joystickSensibility = newJoystickSensibility;
            this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
        };
        VirtualJoystick.prototype._onPointerDown = function (e) {
            var positionOnScreenCondition;
            e.preventDefault();
            if (this._leftJoystick === true) {
                positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
            }
            else {
                positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
            }
            if (positionOnScreenCondition && this._joystickPointerID < 0) {
                // First contact will be dedicated to the virtual joystick
                this._joystickPointerID = e.pointerId;
                this._joystickPointerStartPos.x = e.clientX;
                this._joystickPointerStartPos.y = e.clientY;
                this._joystickPointerPos = this._joystickPointerStartPos.clone();
                this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
                this._deltaJoystickVector.x = 0;
                this._deltaJoystickVector.y = 0;
                this.pressed = true;
                this._touches.add(e.pointerId.toString(), e);
            }
            else {
                // You can only trigger the action buttons with a joystick declared
                if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
                    this._action();
                    this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
                }
            }
        };
        VirtualJoystick.prototype._onPointerMove = function (e) {
            // If the current pointer is the one associated to the joystick (first touch contact)
            if (this._joystickPointerID == e.pointerId) {
                this._joystickPointerPos.x = e.clientX;
                this._joystickPointerPos.y = e.clientY;
                this._deltaJoystickVector = this._joystickPointerPos.clone();
                this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
                var directionLeftRight = this.reverseLeftRight ? -1 : 1;
                var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
                switch (this._axisTargetedByLeftAndRight) {
                    case JoystickAxis.X:
                        this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
                        break;
                    case JoystickAxis.Y:
                        this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
                        break;
                    case JoystickAxis.Z:
                        this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
                        break;
                }
                var directionUpDown = this.reverseUpDown ? 1 : -1;
                var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
                switch (this._axisTargetedByUpAndDown) {
                    case JoystickAxis.X:
                        this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
                        break;
                    case JoystickAxis.Y:
                        this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
                        break;
                    case JoystickAxis.Z:
                        this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
                        break;
                }
            }
            else {
                var data = this._touches.get(e.pointerId.toString());
                if (data) {
                    data.x = e.clientX;
                    data.y = e.clientY;
                }
            }
        };
        VirtualJoystick.prototype._onPointerUp = function (e) {
            if (this._joystickPointerID == e.pointerId) {
                VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
                VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
                this._joystickPointerID = -1;
                this.pressed = false;
            }
            else {
                var touch = this._touches.get(e.pointerId.toString());
                if (touch) {
                    VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
                }
            }
            this._deltaJoystickVector.x = 0;
            this._deltaJoystickVector.y = 0;
            this._touches.remove(e.pointerId.toString());
        };
        /**
        * Change the color of the virtual joystick
        * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
        */
        VirtualJoystick.prototype.setJoystickColor = function (newColor) {
            this._joystickColor = newColor;
        };
        /**
         * Defines a callback to call when the joystick is touched
         * @param action defines the callback
         */
        VirtualJoystick.prototype.setActionOnTouch = function (action) {
            this._action = action;
        };
        /**
         * Defines which axis you'd like to control for left & right
         * @param axis defines the axis to use
         */
        VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
            switch (axis) {
                case JoystickAxis.X:
                case JoystickAxis.Y:
                case JoystickAxis.Z:
                    this._axisTargetedByLeftAndRight = axis;
                    break;
                default:
                    this._axisTargetedByLeftAndRight = JoystickAxis.X;
                    break;
            }
        };
        /**
         * Defines which axis you'd like to control for up & down
         * @param axis defines the axis to use
         */
        VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
            switch (axis) {
                case JoystickAxis.X:
                case JoystickAxis.Y:
                case JoystickAxis.Z:
                    this._axisTargetedByUpAndDown = axis;
                    break;
                default:
                    this._axisTargetedByUpAndDown = JoystickAxis.Y;
                    break;
            }
        };
        VirtualJoystick.prototype._drawVirtualJoystick = function () {
            var _this = this;
            if (this.pressed) {
                this._touches.forEach(function (key, touch) {
                    if (touch.pointerId === _this._joystickPointerID) {
                        VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
                        VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.lineWidth = 6;
                        VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
                        VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
                        VirtualJoystick.vjCanvasContext.lineWidth = 2;
                        VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
                        VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
                    }
                    else {
                        VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.fillStyle = "white";
                        VirtualJoystick.vjCanvasContext.beginPath();
                        VirtualJoystick.vjCanvasContext.strokeStyle = "red";
                        VirtualJoystick.vjCanvasContext.lineWidth = 6;
                        VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
                        VirtualJoystick.vjCanvasContext.stroke();
                        VirtualJoystick.vjCanvasContext.closePath();
                        touch.prevX = touch.x;
                        touch.prevY = touch.y;
                    }
                });
            }
            requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
        };
        /**
         * Release internal HTML canvas
         */
        VirtualJoystick.prototype.releaseCanvas = function () {
            if (VirtualJoystick.vjCanvas) {
                VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
                VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
                VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
                VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
                window.removeEventListener("resize", this._onResize);
                document.body.removeChild(VirtualJoystick.vjCanvas);
                VirtualJoystick.vjCanvas = null;
            }
        };
        // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
        VirtualJoystick._globalJoystickIndex = 0;
        return VirtualJoystick;
    }());
    BABYLON.VirtualJoystick = VirtualJoystick;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.virtualJoystick.js.map


var BABYLON;
(function (BABYLON) {
    BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
        return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
    });
    /**
     * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
     * It is identical to the Free Camera and simply adds by default a virtual joystick.
     * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
     * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
     */
    var VirtualJoysticksCamera = /** @class */ (function (_super) {
        __extends(VirtualJoysticksCamera, _super);
        /**
         * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
         * It is identical to the Free Camera and simply adds by default a virtual joystick.
         * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
         * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
         * @param name Define the name of the camera in the scene
         * @param position Define the start position of the camera in the scene
         * @param scene Define the scene the camera belongs to
         */
        function VirtualJoysticksCamera(name, position, scene) {
            var _this = _super.call(this, name, position, scene) || this;
            _this.inputs.addVirtualJoystick();
            return _this;
        }
        /**
         * Gets the current object class name.
         * @return the class name
         */
        VirtualJoysticksCamera.prototype.getClassName = function () {
            return "VirtualJoysticksCamera";
        };
        return VirtualJoysticksCamera;
    }(BABYLON.FreeCamera));
    BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.virtualJoysticksCamera.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Manage the Virtual Joystick inputs to control the movement of a free camera.
     * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
     */
    var FreeCameraVirtualJoystickInput = /** @class */ (function () {
        function FreeCameraVirtualJoystickInput() {
        }
        /**
         * Gets the left stick of the virtual joystick.
         * @returns The virtual Joystick
         */
        FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
            return this._leftjoystick;
        };
        /**
         * Gets the right stick of the virtual joystick.
         * @returns The virtual Joystick
         */
        FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
            return this._rightjoystick;
        };
        /**
         * Update the current camera state depending on the inputs that have been used this frame.
         * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
         */
        FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
            if (this._leftjoystick) {
                var camera = this.camera;
                var speed = camera._computeLocalCameraSpeed() * 50;
                var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
                var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
                camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
                camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
                if (!this._leftjoystick.pressed) {
                    this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
                }
                if (!this._rightjoystick.pressed) {
                    this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
                }
            }
        };
        /**
         * Attach the input controls to a specific dom element to get the input from.
         * @param element Defines the element the controls should be listened from
         * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
         */
        FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
            this._leftjoystick = new BABYLON.VirtualJoystick(true);
            this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
            this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
            this._leftjoystick.setJoystickSensibility(0.15);
            this._rightjoystick = new BABYLON.VirtualJoystick(false);
            this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
            this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
            this._rightjoystick.reverseUpDown = true;
            this._rightjoystick.setJoystickSensibility(0.05);
            this._rightjoystick.setJoystickColor("yellow");
        };
        /**
         * Detach the current controls from the specified dom element.
         * @param element Defines the element to stop listening the inputs from
         */
        FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
            this._leftjoystick.releaseCanvas();
            this._rightjoystick.releaseCanvas();
        };
        /**
         * Gets the class name of the current intput.
         * @returns the class name
         */
        FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
            return "FreeCameraVirtualJoystickInput";
        };
        /**
         * Get the friendly name associated with the input class.
         * @returns the input friendly name
         */
        FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
            return "virtualJoystick";
        };
        return FreeCameraVirtualJoystickInput;
    }());
    BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
    BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to specify simplification options
     * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
     */
    var SimplificationSettings = /** @class */ (function () {
        /**
         * Creates a SimplificationSettings
         * @param quality expected quality
         * @param distance distance when this optimized version should be used
         * @param optimizeMesh already optimized mesh
         */
        function SimplificationSettings(
        /** expected quality */
        quality, 
        /** distance when this optimized version should be used */
        distance, 
        /** already optimized mesh  */
        optimizeMesh) {
            this.quality = quality;
            this.distance = distance;
            this.optimizeMesh = optimizeMesh;
        }
        return SimplificationSettings;
    }());
    BABYLON.SimplificationSettings = SimplificationSettings;
    /**
     * Queue used to order the simplification tasks
     * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
     */
    var SimplificationQueue = /** @class */ (function () {
        /**
         * Creates a new queue
         */
        function SimplificationQueue() {
            this.running = false;
            this._simplificationArray = [];
        }
        /**
         * Adds a new simplification task
         * @param task defines a task to add
         */
        SimplificationQueue.prototype.addTask = function (task) {
            this._simplificationArray.push(task);
        };
        /**
         * Execute next task
         */
        SimplificationQueue.prototype.executeNext = function () {
            var task = this._simplificationArray.pop();
            if (task) {
                this.running = true;
                this.runSimplification(task);
            }
            else {
                this.running = false;
            }
        };
        /**
         * Execute a simplification task
         * @param task defines the task to run
         */
        SimplificationQueue.prototype.runSimplification = function (task) {
            var _this = this;
            if (task.parallelProcessing) {
                //parallel simplifier
                task.settings.forEach(function (setting) {
                    var simplifier = _this.getSimplifier(task);
                    simplifier.simplify(setting, function (newMesh) {
                        task.mesh.addLODLevel(setting.distance, newMesh);
                        newMesh.isVisible = true;
                        //check if it is the last
                        if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
                            //all done, run the success callback.
                            task.successCallback();
                        }
                        _this.executeNext();
                    });
                });
            }
            else {
                //single simplifier.
                var simplifier = this.getSimplifier(task);
                var runDecimation = function (setting, callback) {
                    simplifier.simplify(setting, function (newMesh) {
                        task.mesh.addLODLevel(setting.distance, newMesh);
                        newMesh.isVisible = true;
                        //run the next quality level
                        callback();
                    });
                };
                BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
                    runDecimation(task.settings[loop.index], function () {
                        loop.executeNext();
                    });
                }, function () {
                    //execution ended, run the success callback.
                    if (task.successCallback) {
                        task.successCallback();
                    }
                    _this.executeNext();
                });
            }
        };
        SimplificationQueue.prototype.getSimplifier = function (task) {
            switch (task.simplificationType) {
                case SimplificationType.QUADRATIC:
                default:
                    return new QuadraticErrorSimplification(task.mesh);
            }
        };
        return SimplificationQueue;
    }());
    BABYLON.SimplificationQueue = SimplificationQueue;
    /**
     * The implemented types of simplification
     * At the moment only Quadratic Error Decimation is implemented
     * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
     */
    var SimplificationType;
    (function (SimplificationType) {
        /** Quadratic error decimation */
        SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
    })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
    var DecimationTriangle = /** @class */ (function () {
        function DecimationTriangle(vertices) {
            this.vertices = vertices;
            this.error = new Array(4);
            this.deleted = false;
            this.isDirty = false;
            this.deletePending = false;
            this.borderFactor = 0;
        }
        return DecimationTriangle;
    }());
    var DecimationVertex = /** @class */ (function () {
        function DecimationVertex(position, id) {
            this.position = position;
            this.id = id;
            this.isBorder = true;
            this.q = new QuadraticMatrix();
            this.triangleCount = 0;
            this.triangleStart = 0;
            this.originalOffsets = [];
        }
        DecimationVertex.prototype.updatePosition = function (newPosition) {
            this.position.copyFrom(newPosition);
        };
        return DecimationVertex;
    }());
    var QuadraticMatrix = /** @class */ (function () {
        function QuadraticMatrix(data) {
            this.data = new Array(10);
            for (var i = 0; i < 10; ++i) {
                if (data && data[i]) {
                    this.data[i] = data[i];
                }
                else {
                    this.data[i] = 0;
                }
            }
        }
        QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
            var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
                this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
                this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
            return det;
        };
        QuadraticMatrix.prototype.addInPlace = function (matrix) {
            for (var i = 0; i < 10; ++i) {
                this.data[i] += matrix.data[i];
            }
        };
        QuadraticMatrix.prototype.addArrayInPlace = function (data) {
            for (var i = 0; i < 10; ++i) {
                this.data[i] += data[i];
            }
        };
        QuadraticMatrix.prototype.add = function (matrix) {
            var m = new QuadraticMatrix();
            for (var i = 0; i < 10; ++i) {
                m.data[i] = this.data[i] + matrix.data[i];
            }
            return m;
        };
        QuadraticMatrix.FromData = function (a, b, c, d) {
            return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
        };
        //returning an array to avoid garbage collection
        QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
            return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
        };
        return QuadraticMatrix;
    }());
    var Reference = /** @class */ (function () {
        function Reference(vertexId, triangleId) {
            this.vertexId = vertexId;
            this.triangleId = triangleId;
        }
        return Reference;
    }());
    /**
     * An implementation of the Quadratic Error simplification algorithm.
     * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
     * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
     * @author RaananW
     * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
     */
    var QuadraticErrorSimplification = /** @class */ (function () {
        function QuadraticErrorSimplification(_mesh) {
            this._mesh = _mesh;
            this.syncIterations = 5000;
            this.aggressiveness = 7;
            this.decimationIterations = 100;
            this.boundingBoxEpsilon = BABYLON.Epsilon;
        }
        QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
            var _this = this;
            this.initDecimatedMesh();
            //iterating through the submeshes array, one after the other.
            BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
                _this.initWithMesh(loop.index, function () {
                    _this.runDecimation(settings, loop.index, function () {
                        loop.executeNext();
                    });
                }, settings.optimizeMesh);
            }, function () {
                setTimeout(function () {
                    successCallback(_this._reconstructedMesh);
                }, 0);
            });
        };
        QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
            var _this = this;
            var targetCount = ~~(this.triangles.length * settings.quality);
            var deletedTriangles = 0;
            var triangleCount = this.triangles.length;
            var iterationFunction = function (iteration, callback) {
                setTimeout(function () {
                    if (iteration % 5 === 0) {
                        _this.updateMesh(iteration === 0);
                    }
                    for (var i = 0; i < _this.triangles.length; ++i) {
                        _this.triangles[i].isDirty = false;
                    }
                    var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
                    var trianglesIterator = function (i) {
                        var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
                        var t = _this.triangles[tIdx];
                        if (!t) {
                            return;
                        }
                        if (t.error[3] > threshold || t.deleted || t.isDirty) {
                            return;
                        }
                        for (var j = 0; j < 3; ++j) {
                            if (t.error[j] < threshold) {
                                var deleted0 = [];
                                var deleted1 = [];
                                var v0 = t.vertices[j];
                                var v1 = t.vertices[(j + 1) % 3];
                                if (v0.isBorder || v1.isBorder) {
                                    continue;
                                }
                                var p = BABYLON.Vector3.Zero();
                                var n = BABYLON.Vector3.Zero();
                                var uv = BABYLON.Vector2.Zero();
                                var color = new BABYLON.Color4(0, 0, 0, 1);
                                _this.calculateError(v0, v1, p, n, uv, color);
                                var delTr = new Array();
                                if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr)) {
                                    continue;
                                }
                                if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr)) {
                                    continue;
                                }
                                if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0) {
                                    continue;
                                }
                                var uniqueArray = new Array();
                                delTr.forEach(function (deletedT) {
                                    if (uniqueArray.indexOf(deletedT) === -1) {
                                        deletedT.deletePending = true;
                                        uniqueArray.push(deletedT);
                                    }
                                });
                                if (uniqueArray.length % 2 !== 0) {
                                    continue;
                                }
                                v0.q = v1.q.add(v0.q);
                                v0.updatePosition(p);
                                var tStart = _this.references.length;
                                deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
                                deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
                                var tCount = _this.references.length - tStart;
                                if (tCount <= v0.triangleCount) {
                                    if (tCount) {
                                        for (var c = 0; c < tCount; c++) {
                                            _this.references[v0.triangleStart + c] = _this.references[tStart + c];
                                        }
                                    }
                                }
                                else {
                                    v0.triangleStart = tStart;
                                }
                                v0.triangleCount = tCount;
                                break;
                            }
                        }
                    };
                    BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
                }, 0);
            };
            BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
                if (triangleCount - deletedTriangles <= targetCount) {
                    loop.breakLoop();
                }
                else {
                    iterationFunction(loop.index, function () {
                        loop.executeNext();
                    });
                }
            }, function () {
                setTimeout(function () {
                    //reconstruct this part of the mesh
                    _this.reconstructMesh(submeshIndex);
                    successCallback();
                }, 0);
            });
        };
        QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
            var _this = this;
            this.vertices = [];
            this.triangles = [];
            var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this._mesh.getIndices();
            var submesh = this._mesh.subMeshes[submeshIndex];
            var findInVertices = function (positionToSearch) {
                if (optimizeMesh) {
                    for (var ii = 0; ii < _this.vertices.length; ++ii) {
                        if (_this.vertices[ii].position.equals(positionToSearch)) {
                            return _this.vertices[ii];
                        }
                    }
                }
                return null;
            };
            var vertexReferences = [];
            var vertexInit = function (i) {
                if (!positionData) {
                    return;
                }
                var offset = i + submesh.verticesStart;
                var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
                var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
                vertex.originalOffsets.push(offset);
                if (vertex.id === _this.vertices.length) {
                    _this.vertices.push(vertex);
                }
                vertexReferences.push(vertex.id);
            };
            //var totalVertices = mesh.getTotalVertices();
            var totalVertices = submesh.verticesCount;
            BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
                var indicesInit = function (i) {
                    if (!indices) {
                        return;
                    }
                    var offset = (submesh.indexStart / 3) + i;
                    var pos = (offset * 3);
                    var i0 = indices[pos + 0];
                    var i1 = indices[pos + 1];
                    var i2 = indices[pos + 2];
                    var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
                    var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
                    var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
                    var triangle = new DecimationTriangle([v0, v1, v2]);
                    triangle.originalOffset = pos;
                    _this.triangles.push(triangle);
                };
                BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
                    _this.init(callback);
                });
            });
        };
        QuadraticErrorSimplification.prototype.init = function (callback) {
            var _this = this;
            var triangleInit1 = function (i) {
                var t = _this.triangles[i];
                t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
                for (var j = 0; j < 3; j++) {
                    t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
                }
            };
            BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
                var triangleInit2 = function (i) {
                    var t = _this.triangles[i];
                    for (var j = 0; j < 3; ++j) {
                        t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
                    }
                    t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
                };
                BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
                    callback();
                });
            });
        };
        QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
            var newTriangles = [];
            var i;
            for (i = 0; i < this.vertices.length; ++i) {
                this.vertices[i].triangleCount = 0;
            }
            var t;
            var j;
            for (i = 0; i < this.triangles.length; ++i) {
                if (!this.triangles[i].deleted) {
                    t = this.triangles[i];
                    for (j = 0; j < 3; ++j) {
                        t.vertices[j].triangleCount = 1;
                    }
                    newTriangles.push(t);
                }
            }
            var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
            var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
            var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
            var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
            var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
            var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
            var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
            var vertexCount = 0;
            for (i = 0; i < this.vertices.length; ++i) {
                var vertex = this.vertices[i];
                vertex.id = vertexCount;
                if (vertex.triangleCount) {
                    vertex.originalOffsets.forEach(function (originalOffset) {
                        if (!normalData) {
                            return;
                        }
                        newPositionData.push(vertex.position.x);
                        newPositionData.push(vertex.position.y);
                        newPositionData.push(vertex.position.z);
                        newNormalData.push(normalData[originalOffset * 3]);
                        newNormalData.push(normalData[(originalOffset * 3) + 1]);
                        newNormalData.push(normalData[(originalOffset * 3) + 2]);
                        if (uvs && uvs.length) {
                            newUVsData.push(uvs[(originalOffset * 2)]);
                            newUVsData.push(uvs[(originalOffset * 2) + 1]);
                        }
                        else if (colorsData && colorsData.length) {
                            newColorsData.push(colorsData[(originalOffset * 4)]);
                            newColorsData.push(colorsData[(originalOffset * 4) + 1]);
                            newColorsData.push(colorsData[(originalOffset * 4) + 2]);
                            newColorsData.push(colorsData[(originalOffset * 4) + 3]);
                        }
                        ++vertexCount;
                    });
                }
            }
            var startingIndex = this._reconstructedMesh.getTotalIndices();
            var startingVertex = this._reconstructedMesh.getTotalVertices();
            var submeshesArray = this._reconstructedMesh.subMeshes;
            this._reconstructedMesh.subMeshes = [];
            var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
            var originalIndices = this._mesh.getIndices();
            for (i = 0; i < newTriangles.length; ++i) {
                t = newTriangles[i]; //now get the new referencing point for each vertex
                [0, 1, 2].forEach(function (idx) {
                    var id = originalIndices[t.originalOffset + idx];
                    var offset = t.vertices[idx].originalOffsets.indexOf(id);
                    if (offset < 0) {
                        offset = 0;
                    }
                    newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
                });
            }
            //overwriting the old vertex buffers and indices.
            this._reconstructedMesh.setIndices(newIndicesArray);
            this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
            this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
            if (newUVsData.length > 0) {
                this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
            }
            if (newColorsData.length > 0) {
                this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
            }
            //create submesh
            var originalSubmesh = this._mesh.subMeshes[submeshIndex];
            if (submeshIndex > 0) {
                this._reconstructedMesh.subMeshes = [];
                submeshesArray.forEach(function (submesh) {
                    BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
                });
                BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
            }
        };
        QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
            this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
            this._reconstructedMesh.material = this._mesh.material;
            this._reconstructedMesh.parent = this._mesh.parent;
            this._reconstructedMesh.isVisible = false;
            this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
        };
        QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
            for (var i = 0; i < vertex1.triangleCount; ++i) {
                var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
                if (t.deleted) {
                    continue;
                }
                var s = this.references[vertex1.triangleStart + i].vertexId;
                var v1 = t.vertices[(s + 1) % 3];
                var v2 = t.vertices[(s + 2) % 3];
                if ((v1 === vertex2 || v2 === vertex2)) {
                    deletedArray[i] = true;
                    delTr.push(t);
                    continue;
                }
                var d1 = v1.position.subtract(point);
                d1 = d1.normalize();
                var d2 = v2.position.subtract(point);
                d2 = d2.normalize();
                if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999) {
                    return true;
                }
                var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
                deletedArray[i] = false;
                if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2) {
                    return true;
                }
            }
            return false;
        };
        QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
            var newDeleted = deletedTriangles;
            for (var i = 0; i < vertex.triangleCount; ++i) {
                var ref = this.references[vertex.triangleStart + i];
                var t = this.triangles[ref.triangleId];
                if (t.deleted) {
                    continue;
                }
                if (deletedArray[i] && t.deletePending) {
                    t.deleted = true;
                    newDeleted++;
                    continue;
                }
                t.vertices[ref.vertexId] = origVertex;
                t.isDirty = true;
                t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
                t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
                t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
                t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
                this.references.push(ref);
            }
            return newDeleted;
        };
        QuadraticErrorSimplification.prototype.identifyBorder = function () {
            for (var i = 0; i < this.vertices.length; ++i) {
                var vCount = [];
                var vId = [];
                var v = this.vertices[i];
                var j;
                for (j = 0; j < v.triangleCount; ++j) {
                    var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
                    for (var ii = 0; ii < 3; ii++) {
                        var ofs = 0;
                        var vv = triangle.vertices[ii];
                        while (ofs < vCount.length) {
                            if (vId[ofs] === vv.id) {
                                break;
                            }
                            ++ofs;
                        }
                        if (ofs === vCount.length) {
                            vCount.push(1);
                            vId.push(vv.id);
                        }
                        else {
                            vCount[ofs]++;
                        }
                    }
                }
                for (j = 0; j < vCount.length; ++j) {
                    if (vCount[j] === 1) {
                        this.vertices[vId[j]].isBorder = true;
                    }
                    else {
                        this.vertices[vId[j]].isBorder = false;
                    }
                }
            }
        };
        QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
            if (identifyBorders === void 0) { identifyBorders = false; }
            var i;
            if (!identifyBorders) {
                var newTrianglesVector = [];
                for (i = 0; i < this.triangles.length; ++i) {
                    if (!this.triangles[i].deleted) {
                        newTrianglesVector.push(this.triangles[i]);
                    }
                }
                this.triangles = newTrianglesVector;
            }
            for (i = 0; i < this.vertices.length; ++i) {
                this.vertices[i].triangleCount = 0;
                this.vertices[i].triangleStart = 0;
            }
            var t;
            var j;
            var v;
            for (i = 0; i < this.triangles.length; ++i) {
                t = this.triangles[i];
                for (j = 0; j < 3; ++j) {
                    v = t.vertices[j];
                    v.triangleCount++;
                }
            }
            var tStart = 0;
            for (i = 0; i < this.vertices.length; ++i) {
                this.vertices[i].triangleStart = tStart;
                tStart += this.vertices[i].triangleCount;
                this.vertices[i].triangleCount = 0;
            }
            var newReferences = new Array(this.triangles.length * 3);
            for (i = 0; i < this.triangles.length; ++i) {
                t = this.triangles[i];
                for (j = 0; j < 3; ++j) {
                    v = t.vertices[j];
                    newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
                    v.triangleCount++;
                }
            }
            this.references = newReferences;
            if (identifyBorders) {
                this.identifyBorder();
            }
        };
        QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
            var x = point.x;
            var y = point.y;
            var z = point.z;
            return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y
                + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
        };
        QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
            var q = vertex1.q.add(vertex2.q);
            var border = vertex1.isBorder && vertex2.isBorder;
            var error = 0;
            var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
            if (qDet !== 0 && !border) {
                if (!pointResult) {
                    pointResult = BABYLON.Vector3.Zero();
                }
                pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
                pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
                pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
                error = this.vertexError(q, pointResult);
            }
            else {
                var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
                //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
                var error1 = this.vertexError(q, vertex1.position);
                var error2 = this.vertexError(q, vertex2.position);
                var error3 = this.vertexError(q, p3);
                error = Math.min(error1, error2, error3);
                if (error === error1) {
                    if (pointResult) {
                        pointResult.copyFrom(vertex1.position);
                    }
                }
                else if (error === error2) {
                    if (pointResult) {
                        pointResult.copyFrom(vertex2.position);
                    }
                }
                else {
                    if (pointResult) {
                        pointResult.copyFrom(p3);
                    }
                }
            }
            return error;
        };
        return QuadraticErrorSimplification;
    }());
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.meshSimplification.js.map

var BABYLON;
(function (BABYLON) {
    Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
        get: function () {
            if (!this._simplificationQueue) {
                this._simplificationQueue = new BABYLON.SimplificationQueue();
                var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
                if (!component) {
                    component = new SimplicationQueueSceneComponent(this);
                    this._addComponent(component);
                }
            }
            return this._simplificationQueue;
        },
        set: function (value) {
            this._simplificationQueue = value;
        },
        enumerable: true,
        configurable: true
    });
    BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
        if (parallelProcessing === void 0) { parallelProcessing = true; }
        if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
        this.getScene().simplificationQueue.addTask({
            settings: settings,
            parallelProcessing: parallelProcessing,
            mesh: this,
            simplificationType: simplificationType,
            successCallback: successCallback
        });
        return this;
    };
    /**
     * Defines the simplification queue scene component responsible to help scheduling the various simplification task
     * created in a scene
     */
    var SimplicationQueueSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function SimplicationQueueSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
            this.scene = scene;
        }
        /**
         * Registers the component in a given scene
         */
        SimplicationQueueSceneComponent.prototype.register = function () {
            this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        SimplicationQueueSceneComponent.prototype.rebuild = function () {
            // Nothing to do for this component
        };
        /**
         * Disposes the component and the associated ressources
         */
        SimplicationQueueSceneComponent.prototype.dispose = function () {
            // Nothing to do for this component
        };
        SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
            if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
                this.scene._simplificationQueue.executeNext();
            }
        };
        return SimplicationQueueSceneComponent;
    }());
    BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to represent a specific level of detail of a mesh
     * @see http://doc.babylonjs.com/how_to/how_to_use_lod
     */
    var MeshLODLevel = /** @class */ (function () {
        /**
         * Creates a new LOD level
         * @param distance defines the distance where this level should star being displayed
         * @param mesh defines the mesh to use to render this level
         */
        function MeshLODLevel(
        /** Defines the distance where this level should star being displayed */
        distance, 
        /** Defines the mesh to use to render this level */
        mesh) {
            this.distance = distance;
            this.mesh = mesh;
        }
        return MeshLODLevel;
    }());
    BABYLON.MeshLODLevel = MeshLODLevel;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.meshLODLevel.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Defines the root class used to create scene optimization to use with SceneOptimizer
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var SceneOptimization = /** @class */ (function () {
        /**
         * Creates the SceneOptimization object
         * @param priority defines the priority of this optimization (0 by default which means first in the list)
         * @param desc defines the description associated with the optimization
         */
        function SceneOptimization(
        /**
         * Defines the priority of this optimization (0 by default which means first in the list)
         */
        priority) {
            if (priority === void 0) { priority = 0; }
            this.priority = priority;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @returns description string
         */
        SceneOptimization.prototype.getDescription = function () {
            return "";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        SceneOptimization.prototype.apply = function (scene, optimizer) {
            return true;
        };
        return SceneOptimization;
    }());
    BABYLON.SceneOptimization = SceneOptimization;
    /**
     * Defines an optimization used to reduce the size of render target textures
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var TextureOptimization = /** @class */ (function (_super) {
        __extends(TextureOptimization, _super);
        /**
         * Creates the TextureOptimization object
         * @param priority defines the priority of this optimization (0 by default which means first in the list)
         * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
         * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
         */
        function TextureOptimization(
        /**
         * Defines the priority of this optimization (0 by default which means first in the list)
         */
        priority, 
        /**
         * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
         */
        maximumSize, 
        /**
         * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
         */
        step) {
            if (priority === void 0) { priority = 0; }
            if (maximumSize === void 0) { maximumSize = 1024; }
            if (step === void 0) { step = 0.5; }
            var _this = _super.call(this, priority) || this;
            _this.priority = priority;
            _this.maximumSize = maximumSize;
            _this.step = step;
            return _this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @returns description string
         */
        TextureOptimization.prototype.getDescription = function () {
            return "Reducing render target texture size to " + this.maximumSize;
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        TextureOptimization.prototype.apply = function (scene, optimizer) {
            var allDone = true;
            for (var index = 0; index < scene.textures.length; index++) {
                var texture = scene.textures[index];
                if (!texture.canRescale || texture.getContext) {
                    continue;
                }
                var currentSize = texture.getSize();
                var maxDimension = Math.max(currentSize.width, currentSize.height);
                if (maxDimension > this.maximumSize) {
                    texture.scale(this.step);
                    allDone = false;
                }
            }
            return allDone;
        };
        return TextureOptimization;
    }(SceneOptimization));
    BABYLON.TextureOptimization = TextureOptimization;
    /**
     * Defines an optimization used to increase or decrease the rendering resolution
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var HardwareScalingOptimization = /** @class */ (function (_super) {
        __extends(HardwareScalingOptimization, _super);
        /**
         * Creates the HardwareScalingOptimization object
         * @param priority defines the priority of this optimization (0 by default which means first in the list)
         * @param maximumScale defines the maximum scale to use (2 by default)
         * @param step defines the step to use between two passes (0.5 by default)
         */
        function HardwareScalingOptimization(
        /**
         * Defines the priority of this optimization (0 by default which means first in the list)
         */
        priority, 
        /**
         * Defines the maximum scale to use (2 by default)
         */
        maximumScale, 
        /**
         * Defines the step to use between two passes (0.5 by default)
         */
        step) {
            if (priority === void 0) { priority = 0; }
            if (maximumScale === void 0) { maximumScale = 2; }
            if (step === void 0) { step = 0.25; }
            var _this = _super.call(this, priority) || this;
            _this.priority = priority;
            _this.maximumScale = maximumScale;
            _this.step = step;
            _this._currentScale = -1;
            _this._directionOffset = 1;
            return _this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        HardwareScalingOptimization.prototype.getDescription = function () {
            return "Setting hardware scaling level to " + this._currentScale;
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
            if (this._currentScale === -1) {
                this._currentScale = scene.getEngine().getHardwareScalingLevel();
                if (this._currentScale > this.maximumScale) {
                    this._directionOffset = -1;
                }
            }
            this._currentScale += this._directionOffset * this.step;
            scene.getEngine().setHardwareScalingLevel(this._currentScale);
            return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
        };
        return HardwareScalingOptimization;
    }(SceneOptimization));
    BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
    /**
     * Defines an optimization used to remove shadows
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var ShadowsOptimization = /** @class */ (function (_super) {
        __extends(ShadowsOptimization, _super);
        function ShadowsOptimization() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        ShadowsOptimization.prototype.getDescription = function () {
            return "Turning shadows on/off";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        ShadowsOptimization.prototype.apply = function (scene, optimizer) {
            scene.shadowsEnabled = optimizer.isInImprovementMode;
            return true;
        };
        return ShadowsOptimization;
    }(SceneOptimization));
    BABYLON.ShadowsOptimization = ShadowsOptimization;
    /**
     * Defines an optimization used to turn post-processes off
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var PostProcessesOptimization = /** @class */ (function (_super) {
        __extends(PostProcessesOptimization, _super);
        function PostProcessesOptimization() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        PostProcessesOptimization.prototype.getDescription = function () {
            return "Turning post-processes on/off";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
            scene.postProcessesEnabled = optimizer.isInImprovementMode;
            return true;
        };
        return PostProcessesOptimization;
    }(SceneOptimization));
    BABYLON.PostProcessesOptimization = PostProcessesOptimization;
    /**
     * Defines an optimization used to turn lens flares off
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var LensFlaresOptimization = /** @class */ (function (_super) {
        __extends(LensFlaresOptimization, _super);
        function LensFlaresOptimization() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        LensFlaresOptimization.prototype.getDescription = function () {
            return "Turning lens flares on/off";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
            scene.lensFlaresEnabled = optimizer.isInImprovementMode;
            return true;
        };
        return LensFlaresOptimization;
    }(SceneOptimization));
    BABYLON.LensFlaresOptimization = LensFlaresOptimization;
    /**
     * Defines an optimization based on user defined callback.
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var CustomOptimization = /** @class */ (function (_super) {
        __extends(CustomOptimization, _super);
        function CustomOptimization() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @returns description string
         */
        CustomOptimization.prototype.getDescription = function () {
            if (this.onGetDescription) {
                return this.onGetDescription();
            }
            return "Running user defined callback";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        CustomOptimization.prototype.apply = function (scene, optimizer) {
            if (this.onApply) {
                return this.onApply(scene, optimizer);
            }
            return true;
        };
        return CustomOptimization;
    }(SceneOptimization));
    BABYLON.CustomOptimization = CustomOptimization;
    /**
     * Defines an optimization used to turn particles off
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var ParticlesOptimization = /** @class */ (function (_super) {
        __extends(ParticlesOptimization, _super);
        function ParticlesOptimization() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        ParticlesOptimization.prototype.getDescription = function () {
            return "Turning particles on/off";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        ParticlesOptimization.prototype.apply = function (scene, optimizer) {
            scene.particlesEnabled = optimizer.isInImprovementMode;
            return true;
        };
        return ParticlesOptimization;
    }(SceneOptimization));
    BABYLON.ParticlesOptimization = ParticlesOptimization;
    /**
     * Defines an optimization used to turn render targets off
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var RenderTargetsOptimization = /** @class */ (function (_super) {
        __extends(RenderTargetsOptimization, _super);
        function RenderTargetsOptimization() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        RenderTargetsOptimization.prototype.getDescription = function () {
            return "Turning render targets off";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @returns true if everything that can be done was applied
         */
        RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
            scene.renderTargetsEnabled = optimizer.isInImprovementMode;
            return true;
        };
        return RenderTargetsOptimization;
    }(SceneOptimization));
    BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
    /**
     * Defines an optimization used to merge meshes with compatible materials
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var MergeMeshesOptimization = /** @class */ (function (_super) {
        __extends(MergeMeshesOptimization, _super);
        function MergeMeshesOptimization() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this._canBeMerged = function (abstractMesh) {
                if (!(abstractMesh instanceof BABYLON.Mesh)) {
                    return false;
                }
                var mesh = abstractMesh;
                if (mesh.isDisposed()) {
                    return false;
                }
                if (!mesh.isVisible || !mesh.isEnabled()) {
                    return false;
                }
                if (mesh.instances.length > 0) {
                    return false;
                }
                if (mesh.skeleton || mesh.hasLODLevels) {
                    return false;
                }
                return true;
            };
            return _this;
        }
        Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
            /**
             * Gets or sets a boolean which defines if optimization octree has to be updated
             */
            get: function () {
                return MergeMeshesOptimization._UpdateSelectionTree;
            },
            /**
             * Gets or sets a boolean which defines if optimization octree has to be updated
             */
            set: function (value) {
                MergeMeshesOptimization._UpdateSelectionTree = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets a string describing the action executed by the current optimization
         * @return description string
         */
        MergeMeshesOptimization.prototype.getDescription = function () {
            return "Merging similar meshes together";
        };
        /**
         * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
         * @param scene defines the current scene where to apply this optimization
         * @param optimizer defines the current optimizer
         * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
         * @returns true if everything that can be done was applied
         */
        MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
            var globalPool = scene.meshes.slice(0);
            var globalLength = globalPool.length;
            for (var index = 0; index < globalLength; index++) {
                var currentPool = new Array();
                var current = globalPool[index];
                // Checks
                if (!this._canBeMerged(current)) {
                    continue;
                }
                currentPool.push(current);
                // Find compatible meshes
                for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
                    var otherMesh = globalPool[subIndex];
                    if (!this._canBeMerged(otherMesh)) {
                        continue;
                    }
                    if (otherMesh.material !== current.material) {
                        continue;
                    }
                    if (otherMesh.checkCollisions !== current.checkCollisions) {
                        continue;
                    }
                    currentPool.push(otherMesh);
                    globalLength--;
                    globalPool.splice(subIndex, 1);
                    subIndex--;
                }
                if (currentPool.length < 2) {
                    continue;
                }
                // Merge meshes
                BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
            }
            // Call the octree system optimization if it is defined.
            var sceneAsAny = scene;
            if (sceneAsAny.createOrUpdateSelectionOctree) {
                if (updateSelectionTree != undefined) {
                    if (updateSelectionTree) {
                        sceneAsAny.createOrUpdateSelectionOctree();
                    }
                }
                else if (MergeMeshesOptimization.UpdateSelectionTree) {
                    sceneAsAny.createOrUpdateSelectionOctree();
                }
            }
            return true;
        };
        MergeMeshesOptimization._UpdateSelectionTree = false;
        return MergeMeshesOptimization;
    }(SceneOptimization));
    BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
    /**
     * Defines a list of options used by SceneOptimizer
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var SceneOptimizerOptions = /** @class */ (function () {
        /**
         * Creates a new list of options used by SceneOptimizer
         * @param targetFrameRate defines the target frame rate to reach (60 by default)
         * @param trackerDuration defines the interval between two checkes (2000ms by default)
         */
        function SceneOptimizerOptions(
        /**
         * Defines the target frame rate to reach (60 by default)
         */
        targetFrameRate, 
        /**
         * Defines the interval between two checkes (2000ms by default)
         */
        trackerDuration) {
            if (targetFrameRate === void 0) { targetFrameRate = 60; }
            if (trackerDuration === void 0) { trackerDuration = 2000; }
            this.targetFrameRate = targetFrameRate;
            this.trackerDuration = trackerDuration;
            /**
             * Gets the list of optimizations to apply
             */
            this.optimizations = new Array();
        }
        /**
         * Add a new optimization
         * @param optimization defines the SceneOptimization to add to the list of active optimizations
         * @returns the current SceneOptimizerOptions
         */
        SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
            this.optimizations.push(optimization);
            return this;
        };
        /**
         * Add a new custom optimization
         * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
         * @param onGetDescription defines the callback called to get the description attached with the optimization.
         * @param priority defines the priority of this optimization (0 by default which means first in the list)
         * @returns the current SceneOptimizerOptions
         */
        SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
            if (priority === void 0) { priority = 0; }
            var optimization = new CustomOptimization(priority);
            optimization.onApply = onApply;
            optimization.onGetDescription = onGetDescription;
            this.optimizations.push(optimization);
            return this;
        };
        /**
         * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
         * @param targetFrameRate defines the target frame rate (60 by default)
         * @returns a SceneOptimizerOptions object
         */
        SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
            var result = new SceneOptimizerOptions(targetFrameRate);
            var priority = 0;
            result.addOptimization(new MergeMeshesOptimization(priority));
            result.addOptimization(new ShadowsOptimization(priority));
            result.addOptimization(new LensFlaresOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new PostProcessesOptimization(priority));
            result.addOptimization(new ParticlesOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new TextureOptimization(priority, 1024));
            return result;
        };
        /**
         * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
         * @param targetFrameRate defines the target frame rate (60 by default)
         * @returns a SceneOptimizerOptions object
         */
        SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
            var result = new SceneOptimizerOptions(targetFrameRate);
            var priority = 0;
            result.addOptimization(new MergeMeshesOptimization(priority));
            result.addOptimization(new ShadowsOptimization(priority));
            result.addOptimization(new LensFlaresOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new PostProcessesOptimization(priority));
            result.addOptimization(new ParticlesOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new TextureOptimization(priority, 512));
            // Next priority
            priority++;
            result.addOptimization(new RenderTargetsOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new HardwareScalingOptimization(priority, 2));
            return result;
        };
        /**
         * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
         * @param targetFrameRate defines the target frame rate (60 by default)
         * @returns a SceneOptimizerOptions object
         */
        SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
            var result = new SceneOptimizerOptions(targetFrameRate);
            var priority = 0;
            result.addOptimization(new MergeMeshesOptimization(priority));
            result.addOptimization(new ShadowsOptimization(priority));
            result.addOptimization(new LensFlaresOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new PostProcessesOptimization(priority));
            result.addOptimization(new ParticlesOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new TextureOptimization(priority, 256));
            // Next priority
            priority++;
            result.addOptimization(new RenderTargetsOptimization(priority));
            // Next priority
            priority++;
            result.addOptimization(new HardwareScalingOptimization(priority, 4));
            return result;
        };
        return SceneOptimizerOptions;
    }());
    BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
    /**
     * Class used to run optimizations in order to reach a target frame rate
     * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
     */
    var SceneOptimizer = /** @class */ (function () {
        /**
         * Creates a new SceneOptimizer
         * @param scene defines the scene to work on
         * @param options defines the options to use with the SceneOptimizer
         * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
         * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
         */
        function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
            if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
            if (improvementMode === void 0) { improvementMode = false; }
            var _this = this;
            this._isRunning = false;
            this._currentPriorityLevel = 0;
            this._targetFrameRate = 60;
            this._trackerDuration = 2000;
            this._currentFrameRate = 0;
            this._improvementMode = false;
            /**
             * Defines an observable called when the optimizer reaches the target frame rate
             */
            this.onSuccessObservable = new BABYLON.Observable();
            /**
             * Defines an observable called when the optimizer enables an optimization
             */
            this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
            /**
             * Defines an observable called when the optimizer is not able to reach the target frame rate
             */
            this.onFailureObservable = new BABYLON.Observable();
            if (!options) {
                this._options = new SceneOptimizerOptions();
            }
            else {
                this._options = options;
            }
            if (this._options.targetFrameRate) {
                this._targetFrameRate = this._options.targetFrameRate;
            }
            if (this._options.trackerDuration) {
                this._trackerDuration = this._options.trackerDuration;
            }
            if (autoGeneratePriorities) {
                var priority = 0;
                for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
                    var optim = _a[_i];
                    optim.priority = priority++;
                }
            }
            this._improvementMode = improvementMode;
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
                _this._sceneDisposeObserver = null;
                _this.dispose();
            });
        }
        Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
            /**
             * Gets a boolean indicating if the optimizer is in improvement mode
             */
            get: function () {
                return this._improvementMode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
            /**
             * Gets the current priority level (0 at start)
             */
            get: function () {
                return this._currentPriorityLevel;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
            /**
             * Gets the current frame rate checked by the SceneOptimizer
             */
            get: function () {
                return this._currentFrameRate;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
            /**
             * Gets or sets the current target frame rate (60 by default)
             */
            get: function () {
                return this._targetFrameRate;
            },
            /**
             * Gets or sets the current target frame rate (60 by default)
             */
            set: function (value) {
                this._targetFrameRate = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
            /**
             * Gets or sets the current interval between two checks (every 2000ms by default)
             */
            get: function () {
                return this._trackerDuration;
            },
            /**
             * Gets or sets the current interval between two checks (every 2000ms by default)
             */
            set: function (value) {
                this._trackerDuration = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
            /**
             * Gets the list of active optimizations
             */
            get: function () {
                return this._options.optimizations;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Stops the current optimizer
         */
        SceneOptimizer.prototype.stop = function () {
            this._isRunning = false;
        };
        /**
         * Reset the optimizer to initial step (current priority level = 0)
         */
        SceneOptimizer.prototype.reset = function () {
            this._currentPriorityLevel = 0;
        };
        /**
         * Start the optimizer. By default it will try to reach a specific framerate
         * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
         */
        SceneOptimizer.prototype.start = function () {
            var _this = this;
            if (this._isRunning) {
                return;
            }
            this._isRunning = true;
            // Let's wait for the scene to be ready before running our check
            this._scene.executeWhenReady(function () {
                setTimeout(function () {
                    _this._checkCurrentState();
                }, _this._trackerDuration);
            });
        };
        SceneOptimizer.prototype._checkCurrentState = function () {
            var _this = this;
            if (!this._isRunning) {
                return;
            }
            var scene = this._scene;
            var options = this._options;
            this._currentFrameRate = Math.round(scene.getEngine().getFps());
            if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
                !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
                this._isRunning = false;
                this.onSuccessObservable.notifyObservers(this);
                return;
            }
            // Apply current level of optimizations
            var allDone = true;
            var noOptimizationApplied = true;
            for (var index = 0; index < options.optimizations.length; index++) {
                var optimization = options.optimizations[index];
                if (optimization.priority === this._currentPriorityLevel) {
                    noOptimizationApplied = false;
                    allDone = allDone && optimization.apply(scene, this);
                    this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
                }
            }
            // If no optimization was applied, this is a failure :(
            if (noOptimizationApplied) {
                this._isRunning = false;
                this.onFailureObservable.notifyObservers(this);
                return;
            }
            // If all optimizations were done, move to next level
            if (allDone) {
                this._currentPriorityLevel++;
            }
            // Let's the system running for a specific amount of time before checking FPS
            scene.executeWhenReady(function () {
                setTimeout(function () {
                    _this._checkCurrentState();
                }, _this._trackerDuration);
            });
        };
        /**
         * Release all resources
         */
        SceneOptimizer.prototype.dispose = function () {
            this.stop();
            this.onSuccessObservable.clear();
            this.onFailureObservable.clear();
            this.onNewOptimizationAppliedObservable.clear();
            if (this._sceneDisposeObserver) {
                this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
            }
        };
        /**
         * Helper function to create a SceneOptimizer with one single line of code
         * @param scene defines the scene to work on
         * @param options defines the options to use with the SceneOptimizer
         * @param onSuccess defines a callback to call on success
         * @param onFailure defines a callback to call on failure
         * @returns the new SceneOptimizer object
         */
        SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
            var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
            if (onSuccess) {
                optimizer.onSuccessObservable.add(function () {
                    onSuccess();
                });
            }
            if (onFailure) {
                optimizer.onFailureObservable.add(function () {
                    onFailure();
                });
            }
            optimizer.start();
            return optimizer;
        };
        return SceneOptimizer;
    }());
    BABYLON.SceneOptimizer = SceneOptimizer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sceneOptimizer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Gets the outline renderer associated with the scene
     * @returns a OutlineRenderer
     */
    BABYLON.Scene.prototype.getOutlineRenderer = function () {
        if (!this._outlineRenderer) {
            this._outlineRenderer = new OutlineRenderer(this);
        }
        return this._outlineRenderer;
    };
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
        get: function () {
            return this._renderOutline;
        },
        set: function (value) {
            if (value) {
                // Lazy Load the component.
                this.getScene().getOutlineRenderer();
            }
            this._renderOutline = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
        get: function () {
            return this._renderOverlay;
        },
        set: function (value) {
            if (value) {
                // Lazy Load the component.
                this.getScene().getOutlineRenderer();
            }
            this._renderOverlay = value;
        },
        enumerable: true,
        configurable: true
    });
    /**
     * This class is responsible to draw bothe outline/overlay of meshes.
     * It should not be used directly but through the available method on mesh.
     */
    var OutlineRenderer = /** @class */ (function () {
        /**
         * Instantiates a new outline renderer. (There could be only one per scene).
         * @param scene Defines the scene it belongs to
         */
        function OutlineRenderer(scene) {
            /**
             * The name of the component. Each component must have a unique name.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
            /**
             * Defines a zOffset to prevent zFighting between the overlay and the mesh.
             */
            this.zOffset = 1;
            this.scene = scene;
            this._engine = scene.getEngine();
            this.scene._addComponent(this);
        }
        /**
         * Register the component to one instance of a scene.
         */
        OutlineRenderer.prototype.register = function () {
            this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
            this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        OutlineRenderer.prototype.rebuild = function () {
            // Nothing to do here.
        };
        /**
         * Disposes the component and the associated ressources.
         */
        OutlineRenderer.prototype.dispose = function () {
            // Nothing to do here.
        };
        /**
         * Renders the outline in the canvas.
         * @param subMesh Defines the sumesh to render
         * @param batch Defines the batch of meshes in case of instances
         * @param useOverlay Defines if the rendering is for the overlay or the outline
         */
        OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
            var _this = this;
            if (useOverlay === void 0) { useOverlay = false; }
            var scene = this.scene;
            var engine = scene.getEngine();
            var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
            if (!this.isReady(subMesh, hardwareInstancedRendering)) {
                return;
            }
            var mesh = subMesh.getRenderingMesh();
            var material = subMesh.getMaterial();
            if (!material || !scene.activeCamera) {
                return;
            }
            engine.enableEffect(this._effect);
            // Logarithmic depth
            if (material.useLogarithmicDepth) {
                this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
            }
            this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
            this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
            this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
            }
            mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
            // Alpha test
            if (material && material.needAlphaTesting()) {
                var alphaTexture = material.getAlphaTestTexture();
                if (alphaTexture) {
                    this._effect.setTexture("diffuseSampler", alphaTexture);
                    this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
                }
            }
            engine.setZOffset(-this.zOffset);
            mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
            engine.setZOffset(0);
        };
        /**
         * Returns whether or not the outline renderer is ready for a given submesh.
         * All the dependencies e.g. submeshes, texture, effect... mus be ready
         * @param subMesh Defines the submesh to check readyness for
         * @param useInstances Defines wheter wee are trying to render instances or not
         * @returns true if ready otherwise false
         */
        OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
            var mesh = subMesh.getMesh();
            var material = subMesh.getMaterial();
            if (material) {
                // Alpha test
                if (material.needAlphaTesting()) {
                    defines.push("#define ALPHATEST");
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                        attribs.push(BABYLON.VertexBuffer.UVKind);
                        defines.push("#define UV1");
                    }
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
                        attribs.push(BABYLON.VertexBuffer.UV2Kind);
                        defines.push("#define UV2");
                    }
                }
                //Logarithmic depth
                if (material.useLogarithmicDepth) {
                    defines.push("#define LOGARITHMICDEPTH");
                }
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
            }
            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("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
            }
            return this._effect.isReady();
        };
        OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
            // Outline - step 1
            this._savedDepthWrite = this._engine.getDepthWrite();
            if (mesh.renderOutline) {
                this._engine.setDepthWrite(false);
                this.render(subMesh, batch);
                this._engine.setDepthWrite(this._savedDepthWrite);
            }
        };
        OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
            // Outline - step 2
            if (mesh.renderOutline && this._savedDepthWrite) {
                this._engine.setDepthWrite(true);
                this._engine.setColorWrite(false);
                this.render(subMesh, batch);
                this._engine.setColorWrite(true);
            }
            // Overlay
            if (mesh.renderOverlay) {
                var currentMode = this._engine.getAlphaMode();
                this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
                this.render(subMesh, batch, true);
                this._engine.setAlphaMode(currentMode);
            }
        };
        return OutlineRenderer;
    }());
    BABYLON.OutlineRenderer = OutlineRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.outlineRenderer.js.map

var BABYLON;
(function (BABYLON) {
    BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
        if (this._edgesRenderer) {
            this._edgesRenderer.dispose();
            this._edgesRenderer = null;
        }
        return this;
    };
    BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
        if (epsilon === void 0) { epsilon = 0.95; }
        if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
        this.disableEdgesRendering();
        this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
        return this;
    };
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
        get: function () {
            return this._edgesRenderer;
        },
        enumerable: true,
        configurable: true
    });
    BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
        if (epsilon === void 0) { epsilon = 0.95; }
        if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
        this.disableEdgesRendering();
        this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
        return this;
    };
    /**
     * FaceAdjacencies Helper class to generate edges
     */
    var FaceAdjacencies = /** @class */ (function () {
        function FaceAdjacencies() {
            this.edges = new Array();
            this.edgesConnectedCount = 0;
        }
        return FaceAdjacencies;
    }());
    /**
     * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
     */
    var EdgesRenderer = /** @class */ (function () {
        /**
         * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
         * Beware when you use this class with complex objects as the adjacencies computation can be really long
         * @param  source Mesh used to create edges
         * @param  epsilon sum of angles in adjacency to check for edge
         * @param  checkVerticesInsteadOfIndices
         * @param  generateEdgesLines - should generate Lines or only prepare resources.
         */
        function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
            if (epsilon === void 0) { epsilon = 0.95; }
            if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
            if (generateEdgesLines === void 0) { generateEdgesLines = true; }
            var _this = this;
            /**
             * Define the size of the edges with an orthographic camera
             */
            this.edgesWidthScalerForOrthographic = 1000.0;
            /**
             * Define the size of the edges with a perspective camera
             */
            this.edgesWidthScalerForPerspective = 50.0;
            this._linesPositions = new Array();
            this._linesNormals = new Array();
            this._linesIndices = new Array();
            this._buffers = {};
            this._checkVerticesInsteadOfIndices = false;
            /** Gets or sets a boolean indicating if the edgesRenderer is active */
            this.isEnabled = true;
            this._source = source;
            this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
            this._epsilon = epsilon;
            this._prepareRessources();
            if (generateEdgesLines) {
                this._generateEdgesLines();
            }
            this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
                _this._rebuild();
            });
            this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
                _this.dispose();
            });
        }
        EdgesRenderer.prototype._prepareRessources = function () {
            if (this._lineShader) {
                return;
            }
            this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
                attributes: ["position", "normal"],
                uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
            });
            this._lineShader.disableDepthWrite = true;
            this._lineShader.backFaceCulling = false;
        };
        /** @hidden */
        EdgesRenderer.prototype._rebuild = function () {
            var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer._rebuild();
            }
            buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
            if (buffer) {
                buffer._rebuild();
            }
            var scene = this._source.getScene();
            var engine = scene.getEngine();
            this._ib = engine.createIndexBuffer(this._linesIndices);
        };
        /**
         * Releases the required resources for the edges renderer
         */
        EdgesRenderer.prototype.dispose = function () {
            this._source.onRebuildObservable.remove(this._meshRebuildObserver);
            this._source.onDisposeObservable.remove(this._meshDisposeObserver);
            var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
            if (buffer) {
                buffer.dispose();
                this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
            if (buffer) {
                buffer.dispose();
                this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
            }
            this._source.getScene().getEngine()._releaseBuffer(this._ib);
            this._lineShader.dispose();
        };
        EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
            if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
                return 0;
            }
            if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
                return 1;
            }
            if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
                return 2;
            }
            return -1;
        };
        EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
            if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
                return 0;
            }
            if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
                return 1;
            }
            if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
                return 2;
            }
            return -1;
        };
        /**
         * Checks if the pair of p0 and p1 is en edge
         * @param faceIndex
         * @param edge
         * @param faceNormals
         * @param  p0
         * @param  p1
         * @private
         */
        EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
            var needToCreateLine;
            if (edge === undefined) {
                needToCreateLine = true;
            }
            else {
                var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
                needToCreateLine = dotProduct < this._epsilon;
            }
            if (needToCreateLine) {
                var offset = this._linesPositions.length / 3;
                var normal = p0.subtract(p1);
                normal.normalize();
                // Positions
                this._linesPositions.push(p0.x);
                this._linesPositions.push(p0.y);
                this._linesPositions.push(p0.z);
                this._linesPositions.push(p0.x);
                this._linesPositions.push(p0.y);
                this._linesPositions.push(p0.z);
                this._linesPositions.push(p1.x);
                this._linesPositions.push(p1.y);
                this._linesPositions.push(p1.z);
                this._linesPositions.push(p1.x);
                this._linesPositions.push(p1.y);
                this._linesPositions.push(p1.z);
                // Normals
                this._linesNormals.push(p1.x);
                this._linesNormals.push(p1.y);
                this._linesNormals.push(p1.z);
                this._linesNormals.push(-1);
                this._linesNormals.push(p1.x);
                this._linesNormals.push(p1.y);
                this._linesNormals.push(p1.z);
                this._linesNormals.push(1);
                this._linesNormals.push(p0.x);
                this._linesNormals.push(p0.y);
                this._linesNormals.push(p0.z);
                this._linesNormals.push(-1);
                this._linesNormals.push(p0.x);
                this._linesNormals.push(p0.y);
                this._linesNormals.push(p0.z);
                this._linesNormals.push(1);
                // Indices
                this._linesIndices.push(offset);
                this._linesIndices.push(offset + 1);
                this._linesIndices.push(offset + 2);
                this._linesIndices.push(offset);
                this._linesIndices.push(offset + 2);
                this._linesIndices.push(offset + 3);
            }
        };
        /**
         * Generates lines edges from adjacencjes
         * @private
         */
        EdgesRenderer.prototype._generateEdgesLines = function () {
            var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this._source.getIndices();
            if (!indices || !positions) {
                return;
            }
            // First let's find adjacencies
            var adjacencies = new Array();
            var faceNormals = new Array();
            var index;
            var faceAdjacencies;
            // Prepare faces
            for (index = 0; index < indices.length; index += 3) {
                faceAdjacencies = new FaceAdjacencies();
                var p0Index = indices[index];
                var p1Index = indices[index + 1];
                var p2Index = indices[index + 2];
                faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
                faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
                faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
                var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
                faceNormal.normalize();
                faceNormals.push(faceNormal);
                adjacencies.push(faceAdjacencies);
            }
            // Scan
            for (index = 0; index < adjacencies.length; index++) {
                faceAdjacencies = adjacencies[index];
                for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
                    var otherFaceAdjacencies = adjacencies[otherIndex];
                    if (faceAdjacencies.edgesConnectedCount === 3) { // Full
                        break;
                    }
                    if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
                        continue;
                    }
                    var otherP0 = indices[otherIndex * 3];
                    var otherP1 = indices[otherIndex * 3 + 1];
                    var otherP2 = indices[otherIndex * 3 + 2];
                    for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
                        var otherEdgeIndex = 0;
                        if (faceAdjacencies.edges[edgeIndex] !== undefined) {
                            continue;
                        }
                        switch (edgeIndex) {
                            case 0:
                                if (this._checkVerticesInsteadOfIndices) {
                                    otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
                                }
                                else {
                                    otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
                                }
                                break;
                            case 1:
                                if (this._checkVerticesInsteadOfIndices) {
                                    otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
                                }
                                else {
                                    otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
                                }
                                break;
                            case 2:
                                if (this._checkVerticesInsteadOfIndices) {
                                    otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
                                }
                                else {
                                    otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
                                }
                                break;
                        }
                        if (otherEdgeIndex === -1) {
                            continue;
                        }
                        faceAdjacencies.edges[edgeIndex] = otherIndex;
                        otherFaceAdjacencies.edges[otherEdgeIndex] = index;
                        faceAdjacencies.edgesConnectedCount++;
                        otherFaceAdjacencies.edgesConnectedCount++;
                        if (faceAdjacencies.edgesConnectedCount === 3) {
                            break;
                        }
                    }
                }
            }
            // Create lines
            for (index = 0; index < adjacencies.length; index++) {
                // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
                var current = adjacencies[index];
                this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
                this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
                this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
            }
            // Merge into a single mesh
            var engine = this._source.getScene().getEngine();
            this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
            this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
            this._ib = engine.createIndexBuffer(this._linesIndices);
            this._indicesCount = this._linesIndices.length;
        };
        /**
         * Checks wether or not the edges renderer is ready to render.
         * @return true if ready, otherwise false.
         */
        EdgesRenderer.prototype.isReady = function () {
            return this._lineShader.isReady();
        };
        /**
         * Renders the edges of the attached mesh,
         */
        EdgesRenderer.prototype.render = function () {
            var scene = this._source.getScene();
            if (!this.isReady() || !scene.activeCamera) {
                return;
            }
            var engine = scene.getEngine();
            this._lineShader._preBind();
            if (this._source.edgesColor.a !== 1) {
                engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
            }
            else {
                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            }
            // VBOs
            engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
            scene.resetCachedMaterial();
            this._lineShader.setColor4("color", this._source.edgesColor);
            if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
                this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
            }
            else {
                this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
            }
            this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
            this._lineShader.bind(this._source.getWorldMatrix());
            // Draw order
            engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
            this._lineShader.unbind();
        };
        return EdgesRenderer;
    }());
    BABYLON.EdgesRenderer = EdgesRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.edgesRenderer.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * FaceAdjacencies Helper class to generate edges
     */
    var FaceAdjacencies = /** @class */ (function () {
        function FaceAdjacencies() {
            this.edges = new Array();
            this.edgesConnectedCount = 0;
        }
        return FaceAdjacencies;
    }());
    /**
     * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
     */
    var LineEdgesRenderer = /** @class */ (function (_super) {
        __extends(LineEdgesRenderer, _super);
        /**
         * This constructor turns off auto generating edges line in Edges Renderer to make it here.
         * @param  source LineMesh used to generate edges
         * @param  epsilon not important (specified angle for edge detection)
         * @param  checkVerticesInsteadOfIndices not important for LineMesh
         */
        function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
            if (epsilon === void 0) { epsilon = 0.95; }
            if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
            var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
            _this._generateEdgesLines();
            return _this;
        }
        /**
         * Always create the edge since its a line so only important things are p0 and p1
         * @param  faceIndex not important for LineMesh
         * @param  edge not important for LineMesh
         * @param  faceNormals not important for LineMesh
         * @param  p0 beginnig of line
         * @param  p1 end of line
         */
        LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
            var offset = this._linesPositions.length / 3;
            var normal = p0.subtract(p1);
            normal.normalize();
            // Positions
            this._linesPositions.push(p0.x);
            this._linesPositions.push(p0.y);
            this._linesPositions.push(p0.z);
            this._linesPositions.push(p0.x);
            this._linesPositions.push(p0.y);
            this._linesPositions.push(p0.z);
            this._linesPositions.push(p1.x);
            this._linesPositions.push(p1.y);
            this._linesPositions.push(p1.z);
            this._linesPositions.push(p1.x);
            this._linesPositions.push(p1.y);
            this._linesPositions.push(p1.z);
            // Normals
            this._linesNormals.push(p1.x);
            this._linesNormals.push(p1.y);
            this._linesNormals.push(p1.z);
            this._linesNormals.push(-1);
            this._linesNormals.push(p1.x);
            this._linesNormals.push(p1.y);
            this._linesNormals.push(p1.z);
            this._linesNormals.push(1);
            this._linesNormals.push(p0.x);
            this._linesNormals.push(p0.y);
            this._linesNormals.push(p0.z);
            this._linesNormals.push(-1);
            this._linesNormals.push(p0.x);
            this._linesNormals.push(p0.y);
            this._linesNormals.push(p0.z);
            this._linesNormals.push(1);
            // Indices
            this._linesIndices.push(offset);
            this._linesIndices.push(offset + 1);
            this._linesIndices.push(offset + 2);
            this._linesIndices.push(offset);
            this._linesIndices.push(offset + 2);
            this._linesIndices.push(offset + 3);
        };
        /**
         * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
         */
        LineEdgesRenderer.prototype._generateEdgesLines = function () {
            var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
            var indices = this._source.getIndices();
            if (!indices || !positions) {
                return;
            }
            // First let's find adjacencies
            var adjacencies = new Array();
            var faceNormals = new Array();
            var index;
            for (var i = 0; i < (positions.length / 3) - 1; i++) {
                var currentAdjecancy = new FaceAdjacencies();
                currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
                currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
                adjacencies.push(currentAdjecancy);
            }
            // Create lines
            for (index = 0; index < adjacencies.length; index++) {
                // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
                var current = adjacencies[index];
                this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
            }
            // Merge into a single mesh
            var engine = this._source.getScene().getEngine();
            this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
            this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
            this._ib = engine.createIndexBuffer(this._linesIndices);
            this._indicesCount = this._linesIndices.length;
        };
        return LineEdgesRenderer;
    }(BABYLON.EdgesRenderer));
    BABYLON.LineEdgesRenderer = LineEdgesRenderer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.lineEdgesRenderer.js.map

var BABYLON;
(function (BABYLON) {
    // Adds the parser to the scene parsers.
    BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
        if (parsedData.effectLayers) {
            if (!container.effectLayers) {
                container.effectLayers = new Array();
            }
            for (var index = 0; index < parsedData.effectLayers.length; index++) {
                var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
                container.effectLayers.push(effectLayer);
            }
        }
    });
    BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
        var index = this.effectLayers.indexOf(toRemove);
        if (index !== -1) {
            this.effectLayers.splice(index, 1);
        }
        return index;
    };
    BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
        this.effectLayers.push(newEffectLayer);
    };
    /**
     * Defines the layer scene component responsible to manage any effect layers
     * in a given scene.
     */
    var EffectLayerSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function EffectLayerSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
            this._renderEffects = false;
            this._needStencil = false;
            this._previousStencilState = false;
            this.scene = scene;
            this._engine = scene.getEngine();
            scene.effectLayers = new Array();
        }
        /**
         * Registers the component in a given scene
         */
        EffectLayerSceneComponent.prototype.register = function () {
            this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
            this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
            this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
            this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
            this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
            this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        EffectLayerSceneComponent.prototype.rebuild = function () {
            var layers = this.scene.effectLayers;
            for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
                var effectLayer = layers_1[_i];
                effectLayer._rebuild();
            }
        };
        /**
         * Serializes the component data to the specified json object
         * @param serializationObject The object to serialize to
         */
        EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
            // Effect layers
            serializationObject.effectLayers = [];
            var layers = this.scene.effectLayers;
            for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
                var effectLayer = layers_2[_i];
                if (effectLayer.serialize) {
                    serializationObject.effectLayers.push(effectLayer.serialize());
                }
            }
        };
        /**
         * Adds all the element from the container to the scene
         * @param container the container holding the elements
         */
        EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
            var _this = this;
            if (!container.effectLayers) {
                return;
            }
            container.effectLayers.forEach(function (o) {
                _this.scene.addEffectLayer(o);
            });
        };
        /**
         * Removes all the elements in the container from the scene
         * @param container contains the elements to remove
         */
        EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
            var _this = this;
            if (!container.effectLayers) {
                return;
            }
            container.effectLayers.forEach(function (o) {
                _this.scene.removeEffectLayer(o);
            });
        };
        /**
         * Disposes the component and the associated ressources.
         */
        EffectLayerSceneComponent.prototype.dispose = function () {
            var layers = this.scene.effectLayers;
            while (layers.length) {
                layers[0].dispose();
            }
        };
        EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
            var layers = this.scene.effectLayers;
            for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
                var layer = layers_3[_i];
                if (!layer.hasMesh(mesh)) {
                    continue;
                }
                for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
                    var subMesh = _b[_a];
                    if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
                        return false;
                    }
                }
            }
            return true;
        };
        EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
            this._renderEffects = false;
            this._needStencil = false;
            var layers = this.scene.effectLayers;
            if (layers && layers.length > 0) {
                this._previousStencilState = this._engine.getStencilBuffer();
                for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
                    var effectLayer = layers_4[_i];
                    if (effectLayer.shouldRender() &&
                        (!effectLayer.camera ||
                            (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
                            (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
                        this._renderEffects = true;
                        this._needStencil = this._needStencil || effectLayer.needStencil();
                        var renderTarget = effectLayer._mainTexture;
                        if (renderTarget._shouldRender()) {
                            this.scene.incrementRenderId();
                            renderTarget.render(false, false);
                        }
                    }
                }
                this.scene.incrementRenderId();
            }
        };
        EffectLayerSceneComponent.prototype._setStencil = function (camera) {
            // Activate effect Layer stencil
            if (this._needStencil) {
                this._engine.setStencilBuffer(true);
            }
        };
        EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
            // Restore effect Layer stencil
            if (this._needStencil) {
                this._engine.setStencilBuffer(this._previousStencilState);
            }
        };
        EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
            if (this._renderEffects) {
                this._engine.setDepthBuffer(false);
                var layers = this.scene.effectLayers;
                for (var i = 0; i < layers.length; i++) {
                    var effectLayer = layers[i];
                    if (effectLayer.renderingGroupId === renderingGroupId) {
                        if (effectLayer.shouldRender()) {
                            effectLayer.render();
                        }
                    }
                }
                this._engine.setDepthBuffer(true);
            }
        };
        EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
            if (this._renderEffects) {
                this._draw(-1);
            }
        };
        EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
            if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
                this._draw(index);
            }
        };
        return EffectLayerSceneComponent;
    }());
    BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.effectLayerSceneComponent.js.map

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};

var BABYLON;
(function (BABYLON) {
    /**
     * The effect layer Helps adding post process effect blended with the main pass.
     *
     * This can be for instance use to generate glow or higlight effects on the scene.
     *
     * The effect layer class can not be used directly and is intented to inherited from to be
     * customized per effects.
     */
    var EffectLayer = /** @class */ (function () {
        /**
         * Instantiates a new effect Layer and references it in the scene.
         * @param name The name of the layer
         * @param scene The scene to use the layer in
         */
        function EffectLayer(
        /** The Friendly of the effect in the scene */
        name, scene) {
            this._vertexBuffers = {};
            this._maxSize = 0;
            this._mainTextureDesiredSize = { width: 0, height: 0 };
            this._shouldRender = true;
            this._postProcesses = [];
            this._textures = [];
            this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
            /**
             * The clear color of the texture used to generate the glow map.
             */
            this.neutralColor = new BABYLON.Color4();
            /**
             * Specifies wether the highlight layer is enabled or not.
             */
            this.isEnabled = true;
            /**
             * An event triggered when the effect layer has been disposed.
             */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
             * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
             */
            this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
            /**
             * An event triggered when the generated texture is being merged in the scene.
             */
            this.onBeforeComposeObservable = new BABYLON.Observable();
            /**
             * An event triggered when the generated texture has been merged in the scene.
             */
            this.onAfterComposeObservable = new BABYLON.Observable();
            /**
             * An event triggered when the efffect layer changes its size.
             */
            this.onSizeChangedObservable = new BABYLON.Observable();
            this.name = name;
            this._scene = scene || BABYLON.Engine.LastCreatedScene;
            var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
            if (!component) {
                component = new BABYLON.EffectLayerSceneComponent(this._scene);
                this._scene._addComponent(component);
            }
            this._engine = this._scene.getEngine();
            this._maxSize = this._engine.getCaps().maxTextureSize;
            this._scene.effectLayers.push(this);
            // Generate Buffers
            this._generateIndexBuffer();
            this._genrateVertexBuffer();
        }
        Object.defineProperty(EffectLayer.prototype, "camera", {
            /**
             * Gets the camera attached to the layer.
             */
            get: function () {
                return this._effectLayerOptions.camera;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
            /**
             * Gets the rendering group id the layer should render in.
             */
            get: function () {
                return this._effectLayerOptions.renderingGroupId;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Initializes the effect layer with the required options.
         * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
         */
        EffectLayer.prototype._init = function (options) {
            // Adapt options
            this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
            this._setMainTextureSize();
            this._createMainTexture();
            this._createTextureAndPostProcesses();
            this._mergeEffect = this._createMergeEffect();
        };
        /**
         * Generates the index buffer of the full screen quad blending to the main canvas.
         */
        EffectLayer.prototype._generateIndexBuffer = function () {
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = this._engine.createIndexBuffer(indices);
        };
        /**
         * Generates the vertex buffer of the full screen quad blending to the main canvas.
         */
        EffectLayer.prototype._genrateVertexBuffer = function () {
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
        };
        /**
         * Sets the main texture desired size which is the closest power of two
         * of the engine canvas size.
         */
        EffectLayer.prototype._setMainTextureSize = function () {
            if (this._effectLayerOptions.mainTextureFixedSize) {
                this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
                this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
            }
            else {
                this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
                this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
                this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
                this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
            }
            this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
            this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
        };
        /**
         * Creates the main texture for the effect layer.
         */
        EffectLayer.prototype._createMainTexture = function () {
            var _this = this;
            this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
                width: this._mainTextureDesiredSize.width,
                height: this._mainTextureDesiredSize.height
            }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            this._mainTexture.activeCamera = this._effectLayerOptions.camera;
            this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._mainTexture.anisotropicFilteringLevel = 1;
            this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._mainTexture.renderParticles = false;
            this._mainTexture.renderList = null;
            this._mainTexture.ignoreCameraViewport = true;
            // Custom render function
            this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
                _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
                var index;
                var engine = _this._scene.getEngine();
                if (depthOnlySubMeshes.length) {
                    engine.setColorWrite(false);
                    for (index = 0; index < depthOnlySubMeshes.length; index++) {
                        _this._renderSubMesh(depthOnlySubMeshes.data[index]);
                    }
                    engine.setColorWrite(true);
                }
                for (index = 0; index < opaqueSubMeshes.length; index++) {
                    _this._renderSubMesh(opaqueSubMeshes.data[index]);
                }
                for (index = 0; index < alphaTestSubMeshes.length; index++) {
                    _this._renderSubMesh(alphaTestSubMeshes.data[index]);
                }
                for (index = 0; index < transparentSubMeshes.length; index++) {
                    _this._renderSubMesh(transparentSubMeshes.data[index]);
                }
            };
            this._mainTexture.onClearObservable.add(function (engine) {
                engine.clear(_this.neutralColor, true, true, true);
            });
        };
        /**
         * Checks for the readiness of the element composing the layer.
         * @param subMesh the mesh to check for
         * @param useInstances specify wether or not to use instances to render the mesh
         * @param emissiveTexture the associated emissive texture used to generate the glow
         * @return true if ready otherwise, false
         */
        EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
            var material = subMesh.getMaterial();
            if (!material) {
                return false;
            }
            if (!material.isReady(subMesh.getMesh(), useInstances)) {
                return false;
            }
            var defines = [];
            var attribs = [BABYLON.VertexBuffer.PositionKind];
            var mesh = subMesh.getMesh();
            var uv1 = false;
            var uv2 = false;
            // Alpha test
            if (material && material.needAlphaTesting()) {
                var alphaTexture = material.getAlphaTestTexture();
                if (alphaTexture) {
                    defines.push("#define ALPHATEST");
                    if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
                        alphaTexture.coordinatesIndex === 1) {
                        defines.push("#define DIFFUSEUV2");
                        uv2 = true;
                    }
                    else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                        defines.push("#define DIFFUSEUV1");
                        uv1 = true;
                    }
                }
            }
            // Emissive
            if (emissiveTexture) {
                defines.push("#define EMISSIVE");
                if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
                    emissiveTexture.coordinatesIndex === 1) {
                    defines.push("#define EMISSIVEUV2");
                    uv2 = true;
                }
                else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
                    defines.push("#define EMISSIVEUV1");
                    uv1 = true;
                }
            }
            if (uv1) {
                attribs.push(BABYLON.VertexBuffer.UVKind);
                defines.push("#define UV1");
            }
            if (uv2) {
                attribs.push(BABYLON.VertexBuffer.UV2Kind);
                defines.push("#define UV2");
            }
            // Bones
            if (mesh.useBones && mesh.computeBonesUsingShaders) {
                attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
                attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
                if (mesh.numBoneInfluencers > 4) {
                    attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
                    attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
                }
                defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
                defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
            }
            else {
                defines.push("#define NUM_BONE_INFLUENCERS 0");
            }
            // Morph targets
            var manager = mesh.morphTargetManager;
            var morphInfluencers = 0;
            if (manager) {
                if (manager.numInfluencers > 0) {
                    defines.push("#define MORPHTARGETS");
                    morphInfluencers = manager.numInfluencers;
                    defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
                    BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
                }
            }
            // 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._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
            }
            return this._effectLayerMapGenerationEffect.isReady();
        };
        /**
         * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
         */
        EffectLayer.prototype.render = function () {
            var currentEffect = this._mergeEffect;
            // Check
            if (!currentEffect.isReady()) {
                return;
            }
            for (var i = 0; i < this._postProcesses.length; i++) {
                if (!this._postProcesses[i].isReady()) {
                    return;
                }
            }
            var engine = this._scene.getEngine();
            this.onBeforeComposeObservable.notifyObservers(this);
            // Render
            engine.enableEffect(currentEffect);
            engine.setState(false);
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
            // Cache
            var previousAlphaMode = engine.getAlphaMode();
            // Go Blend.
            engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
            // Blends the map on the main canvas.
            this._internalRender(currentEffect);
            // Restore Alpha
            engine.setAlphaMode(previousAlphaMode);
            this.onAfterComposeObservable.notifyObservers(this);
            // Handle size changes.
            var size = this._mainTexture.getSize();
            this._setMainTextureSize();
            if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
                // Recreate RTT and post processes on size change.
                this.onSizeChangedObservable.notifyObservers(this);
                this._disposeTextureAndPostProcesses();
                this._createMainTexture();
                this._createTextureAndPostProcesses();
            }
        };
        /**
         * Determine if a given mesh will be used in the current effect.
         * @param mesh mesh to test
         * @returns true if the mesh will be used
         */
        EffectLayer.prototype.hasMesh = function (mesh) {
            if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
                return true;
            }
            return false;
        };
        /**
         * Returns true if the layer contains information to display, otherwise false.
         * @returns true if the glow layer should be rendered
         */
        EffectLayer.prototype.shouldRender = function () {
            return this.isEnabled && this._shouldRender;
        };
        /**
         * Returns true if the mesh should render, otherwise false.
         * @param mesh The mesh to render
         * @returns true if it should render otherwise false
         */
        EffectLayer.prototype._shouldRenderMesh = function (mesh) {
            return true;
        };
        /**
         * Returns true if the mesh should render, otherwise false.
         * @param mesh The mesh to render
         * @returns true if it should render otherwise false
         */
        EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
            return true;
        };
        /**
         * Renders the submesh passed in parameter to the generation map.
         */
        EffectLayer.prototype._renderSubMesh = function (subMesh) {
            var _this = this;
            if (!this.shouldRender()) {
                return;
            }
            var material = subMesh.getMaterial();
            var mesh = subMesh.getRenderingMesh();
            var scene = this._scene;
            var engine = scene.getEngine();
            if (!material) {
                return;
            }
            // Do not block in blend mode.
            if (material.needAlphaBlendingForMesh(mesh)) {
                return;
            }
            // Culling
            engine.setState(material.backFaceCulling);
            // Managing instances
            var batch = mesh._getInstancesRenderList(subMesh._id);
            if (batch.mustReturn) {
                return;
            }
            // Early Exit per mesh
            if (!this._shouldRenderMesh(mesh)) {
                return;
            }
            var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
            this._setEmissiveTextureAndColor(mesh, subMesh, material);
            if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
                engine.enableEffect(this._effectLayerMapGenerationEffect);
                mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
                this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
                this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
                // Alpha test
                if (material && material.needAlphaTesting()) {
                    var alphaTexture = material.getAlphaTestTexture();
                    if (alphaTexture) {
                        this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
                        var textureMatrix = alphaTexture.getTextureMatrix();
                        if (textureMatrix) {
                            this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
                        }
                    }
                }
                // Glow emissive only
                if (this._emissiveTextureAndColor.texture) {
                    this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
                    this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
                }
                // Bones
                if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
                    this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
                }
                // Morph targets
                BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
                // Draw
                mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
            }
            else {
                // Need to reset refresh rate of the main map
                this._mainTexture.resetRefreshCounter();
            }
        };
        /**
         * Rebuild the required buffers.
         * @hidden Internal use only.
         */
        EffectLayer.prototype._rebuild = function () {
            var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vb) {
                vb._rebuild();
            }
            this._generateIndexBuffer();
        };
        /**
         * Dispose only the render target textures and post process.
         */
        EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
            this._mainTexture.dispose();
            for (var i = 0; i < this._postProcesses.length; i++) {
                if (this._postProcesses[i]) {
                    this._postProcesses[i].dispose();
                }
            }
            this._postProcesses = [];
            for (var i = 0; i < this._textures.length; i++) {
                if (this._textures[i]) {
                    this._textures[i].dispose();
                }
            }
            this._textures = [];
        };
        /**
         * Dispose the highlight layer and free resources.
         */
        EffectLayer.prototype.dispose = function () {
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            // Clean textures and post processes
            this._disposeTextureAndPostProcesses();
            // Remove from scene
            var index = this._scene.effectLayers.indexOf(this, 0);
            if (index > -1) {
                this._scene.effectLayers.splice(index, 1);
            }
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onBeforeRenderMainTextureObservable.clear();
            this.onBeforeComposeObservable.clear();
            this.onAfterComposeObservable.clear();
            this.onSizeChangedObservable.clear();
        };
        /**
          * Gets the class name of the effect layer
          * @returns the string with the class name of the effect layer
          */
        EffectLayer.prototype.getClassName = function () {
            return "EffectLayer";
        };
        /**
         * Creates an effect layer from parsed effect layer data
         * @param parsedEffectLayer defines effect layer data
         * @param scene defines the current scene
         * @param rootUrl defines the root URL containing the effect layer information
         * @returns a parsed effect Layer
         */
        EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
            var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
            return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
        };
        __decorate([
            BABYLON.serialize()
        ], EffectLayer.prototype, "name", void 0);
        __decorate([
            BABYLON.serializeAsColor4()
        ], EffectLayer.prototype, "neutralColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], EffectLayer.prototype, "isEnabled", void 0);
        __decorate([
            BABYLON.serializeAsCameraReference()
        ], EffectLayer.prototype, "camera", null);
        __decorate([
            BABYLON.serialize()
        ], EffectLayer.prototype, "renderingGroupId", null);
        return EffectLayer;
    }());
    BABYLON.EffectLayer = EffectLayer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.effectLayer.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
        for (var index = 0; index < this.effectLayers.length; index++) {
            if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
                return this.effectLayers[index];
            }
        }
        return null;
    };
    /**
     * Special Glow Blur post process only blurring the alpha channel
     * It enforces keeping the most luminous color in the color channel.
     */
    var GlowBlurPostProcess = /** @class */ (function (_super) {
        __extends(GlowBlurPostProcess, _super);
        function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
            var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
            _this.direction = direction;
            _this.kernel = kernel;
            _this.onApplyObservable.add(function (effect) {
                effect.setFloat2("screenSize", _this.width, _this.height);
                effect.setVector2("direction", _this.direction);
                effect.setFloat("blurWidth", _this.kernel);
            });
            return _this;
        }
        return GlowBlurPostProcess;
    }(BABYLON.PostProcess));
    /**
     * The highlight layer Helps adding a glow effect around a mesh.
     *
     * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
     * glowy meshes to your scene.
     *
     * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
     */
    var HighlightLayer = /** @class */ (function (_super) {
        __extends(HighlightLayer, _super);
        /**
         * Instantiates a new highlight Layer and references it to the scene..
         * @param name The name of the layer
         * @param scene The scene to use the layer in
         * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
         */
        function HighlightLayer(name, scene, options) {
            var _this = _super.call(this, name, scene) || this;
            _this.name = name;
            /**
             * Specifies whether or not the inner glow is ACTIVE in the layer.
             */
            _this.innerGlow = true;
            /**
             * Specifies whether or not the outer glow is ACTIVE in the layer.
             */
            _this.outerGlow = true;
            /**
             * An event triggered when the highlight layer is being blurred.
             */
            _this.onBeforeBlurObservable = new BABYLON.Observable();
            /**
             * An event triggered when the highlight layer has been blurred.
             */
            _this.onAfterBlurObservable = new BABYLON.Observable();
            _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
            _this._meshes = {};
            _this._excludedMeshes = {};
            _this.neutralColor = HighlightLayer.NeutralColor;
            // Warn on stencil
            if (!_this._engine.isStencilEnable) {
                BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
            }
            // Adapt options
            _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
            // Initialize the layer
            _this._init({
                alphaBlendingMode: _this._options.alphaBlendingMode,
                camera: _this._options.camera,
                mainTextureFixedSize: _this._options.mainTextureFixedSize,
                mainTextureRatio: _this._options.mainTextureRatio,
                renderingGroupId: _this._options.renderingGroupId
            });
            // Do not render as long as no meshes have been added
            _this._shouldRender = false;
            return _this;
        }
        Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
            /**
             * Gets the horizontal size of the blur.
             */
            get: function () {
                return this._horizontalBlurPostprocess.kernel;
            },
            /**
             * Specifies the horizontal size of the blur.
             */
            set: function (value) {
                this._horizontalBlurPostprocess.kernel = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
            /**
             * Gets the vertical size of the blur.
             */
            get: function () {
                return this._verticalBlurPostprocess.kernel;
            },
            /**
             * Specifies the vertical size of the blur.
             */
            set: function (value) {
                this._verticalBlurPostprocess.kernel = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get the effect name of the layer.
         * @return The effect name
         */
        HighlightLayer.prototype.getEffectName = function () {
            return HighlightLayer.EffectName;
        };
        /**
         * Create the merge effect. This is the shader use to blit the information back
         * to the main canvas at the end of the scene rendering.
         */
        HighlightLayer.prototype._createMergeEffect = function () {
            // Effect
            return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
        };
        /**
         * Creates the render target textures and post processes used in the highlight layer.
         */
        HighlightLayer.prototype._createTextureAndPostProcesses = function () {
            var _this = this;
            var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
            var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
            blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
            blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
            var textureType = 0;
            if (this._engine.getCaps().textureHalfFloatRender) {
                textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
            }
            else {
                textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            }
            this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
                width: blurTextureWidth,
                height: blurTextureHeight
            }, this._scene, false, true, textureType);
            this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture.anisotropicFilteringLevel = 16;
            this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
            this._blurTexture.renderParticles = false;
            this._blurTexture.ignoreCameraViewport = true;
            this._textures = [this._blurTexture];
            if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
                this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._downSamplePostprocess.onApplyObservable.add(function (effect) {
                    effect.setTexture("textureSampler", _this._mainTexture);
                });
                this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
                });
                this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
                this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
                });
                this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
            }
            else {
                this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
                    width: blurTextureWidth,
                    height: blurTextureHeight
                }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
                this._horizontalBlurPostprocess.width = blurTextureWidth;
                this._horizontalBlurPostprocess.height = blurTextureHeight;
                this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
                    effect.setTexture("textureSampler", _this._mainTexture);
                });
                this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
                    width: blurTextureWidth,
                    height: blurTextureHeight
                }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
                this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
            }
            this._mainTexture.onAfterUnbindObservable.add(function () {
                _this.onBeforeBlurObservable.notifyObservers(_this);
                var internalTexture = _this._blurTexture.getInternalTexture();
                if (internalTexture) {
                    _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
                }
                _this.onAfterBlurObservable.notifyObservers(_this);
            });
            // Prevent autoClear.
            this._postProcesses.map(function (pp) { pp.autoClear = false; });
        };
        /**
         * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
         */
        HighlightLayer.prototype.needStencil = function () {
            return true;
        };
        /**
         * Checks for the readiness of the element composing the layer.
         * @param subMesh the mesh to check for
         * @param useInstances specify wether or not to use instances to render the mesh
         * @param emissiveTexture the associated emissive texture used to generate the glow
         * @return true if ready otherwise, false
         */
        HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
            var material = subMesh.getMaterial();
            var mesh = subMesh.getRenderingMesh();
            if (!material || !mesh || !this._meshes) {
                return false;
            }
            var emissiveTexture = null;
            var highlightLayerMesh = this._meshes[mesh.uniqueId];
            if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
                emissiveTexture = material.emissiveTexture;
            }
            return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
        };
        /**
         * Implementation specific of rendering the generating effect on the main canvas.
         * @param effect The effect used to render through
         */
        HighlightLayer.prototype._internalRender = function (effect) {
            // Texture
            effect.setTexture("textureSampler", this._blurTexture);
            // Cache
            var engine = this._engine;
            var previousStencilBuffer = engine.getStencilBuffer();
            var previousStencilFunction = engine.getStencilFunction();
            var previousStencilMask = engine.getStencilMask();
            var previousStencilOperationPass = engine.getStencilOperationPass();
            var previousStencilOperationFail = engine.getStencilOperationFail();
            var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
            var previousStencilReference = engine.getStencilFunctionReference();
            // Stencil operations
            engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
            engine.setStencilOperationFail(BABYLON.Engine.KEEP);
            engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
            // Draw order
            engine.setStencilMask(0x00);
            engine.setStencilBuffer(true);
            engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
            // 2 passes inner outer
            if (this.outerGlow) {
                effect.setFloat("offset", 0);
                engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
            }
            if (this.innerGlow) {
                effect.setFloat("offset", 1);
                engine.setStencilFunction(BABYLON.Engine.EQUAL);
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
            }
            // Restore Cache
            engine.setStencilFunction(previousStencilFunction);
            engine.setStencilMask(previousStencilMask);
            engine.setStencilBuffer(previousStencilBuffer);
            engine.setStencilOperationPass(previousStencilOperationPass);
            engine.setStencilOperationFail(previousStencilOperationFail);
            engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
            engine.setStencilFunctionReference(previousStencilReference);
        };
        /**
         * Returns true if the layer contains information to display, otherwise false.
         */
        HighlightLayer.prototype.shouldRender = function () {
            if (_super.prototype.shouldRender.call(this)) {
                return this._meshes ? true : false;
            }
            return false;
        };
        /**
         * Returns true if the mesh should render, otherwise false.
         * @param mesh The mesh to render
         * @returns true if it should render otherwise false
         */
        HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
            // Excluded Mesh
            if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
                return false;
            }
            if (!_super.prototype.hasMesh.call(this, mesh)) {
                return false;
            }
            return true;
        };
        /**
         * Sets the required values for both the emissive texture and and the main color.
         */
        HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
            var highlightLayerMesh = this._meshes[mesh.uniqueId];
            if (highlightLayerMesh) {
                this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
            }
            else {
                this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
            }
            if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
                this._emissiveTextureAndColor.texture = material.emissiveTexture;
                this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
            }
            else {
                this._emissiveTextureAndColor.texture = null;
            }
        };
        /**
         * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
         * @param mesh The mesh to exclude from the highlight layer
         */
        HighlightLayer.prototype.addExcludedMesh = function (mesh) {
            if (!this._excludedMeshes) {
                return;
            }
            var meshExcluded = this._excludedMeshes[mesh.uniqueId];
            if (!meshExcluded) {
                this._excludedMeshes[mesh.uniqueId] = {
                    mesh: mesh,
                    beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
                        mesh.getEngine().setStencilBuffer(false);
                    }),
                    afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
                        mesh.getEngine().setStencilBuffer(true);
                    }),
                };
            }
        };
        /**
          * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
          * @param mesh The mesh to highlight
          */
        HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
            if (!this._excludedMeshes) {
                return;
            }
            var meshExcluded = this._excludedMeshes[mesh.uniqueId];
            if (meshExcluded) {
                if (meshExcluded.beforeRender) {
                    mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
                }
                if (meshExcluded.afterRender) {
                    mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
                }
            }
            this._excludedMeshes[mesh.uniqueId] = null;
        };
        /**
         * Determine if a given mesh will be highlighted by the current HighlightLayer
         * @param mesh mesh to test
         * @returns true if the mesh will be highlighted by the current HighlightLayer
         */
        HighlightLayer.prototype.hasMesh = function (mesh) {
            if (!this._meshes) {
                return false;
            }
            if (!_super.prototype.hasMesh.call(this, mesh)) {
                return false;
            }
            return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
        };
        /**
         * Add a mesh in the highlight layer in order to make it glow with the chosen color.
         * @param mesh The mesh to highlight
         * @param color The color of the highlight
         * @param glowEmissiveOnly Extract the glow from the emissive texture
         */
        HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
            var _this = this;
            if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
            if (!this._meshes) {
                return;
            }
            var meshHighlight = this._meshes[mesh.uniqueId];
            if (meshHighlight) {
                meshHighlight.color = color;
            }
            else {
                this._meshes[mesh.uniqueId] = {
                    mesh: mesh,
                    color: color,
                    // Lambda required for capture due to Observable this context
                    observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
                        if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
                            _this._defaultStencilReference(mesh);
                        }
                        else {
                            mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
                        }
                    }),
                    observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
                    glowEmissiveOnly: glowEmissiveOnly
                };
                mesh.onDisposeObservable.add(function () {
                    _this._disposeMesh(mesh);
                });
            }
            this._shouldRender = true;
        };
        /**
         * Remove a mesh from the highlight layer in order to make it stop glowing.
         * @param mesh The mesh to highlight
         */
        HighlightLayer.prototype.removeMesh = function (mesh) {
            if (!this._meshes) {
                return;
            }
            var meshHighlight = this._meshes[mesh.uniqueId];
            if (meshHighlight) {
                if (meshHighlight.observerHighlight) {
                    mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
                }
                if (meshHighlight.observerDefault) {
                    mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
                }
                delete this._meshes[mesh.uniqueId];
            }
            this._shouldRender = false;
            for (var meshHighlightToCheck in this._meshes) {
                if (this._meshes[meshHighlightToCheck]) {
                    this._shouldRender = true;
                    break;
                }
            }
        };
        /**
         * Force the stencil to the normal expected value for none glowing parts
         */
        HighlightLayer.prototype._defaultStencilReference = function (mesh) {
            mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
        };
        /**
         * Free any resources and references associated to a mesh.
         * Internal use
         * @param mesh The mesh to free.
         * @hidden
         */
        HighlightLayer.prototype._disposeMesh = function (mesh) {
            this.removeMesh(mesh);
            this.removeExcludedMesh(mesh);
        };
        /**
         * Dispose the highlight layer and free resources.
         */
        HighlightLayer.prototype.dispose = function () {
            if (this._meshes) {
                // Clean mesh references
                for (var id in this._meshes) {
                    var meshHighlight = this._meshes[id];
                    if (meshHighlight && meshHighlight.mesh) {
                        if (meshHighlight.observerHighlight) {
                            meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
                        }
                        if (meshHighlight.observerDefault) {
                            meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
                        }
                    }
                }
                this._meshes = null;
            }
            if (this._excludedMeshes) {
                for (var id in this._excludedMeshes) {
                    var meshHighlight = this._excludedMeshes[id];
                    if (meshHighlight) {
                        if (meshHighlight.beforeRender) {
                            meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
                        }
                        if (meshHighlight.afterRender) {
                            meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
                        }
                    }
                }
                this._excludedMeshes = null;
            }
            _super.prototype.dispose.call(this);
        };
        /**
          * Gets the class name of the effect layer
          * @returns the string with the class name of the effect layer
          */
        HighlightLayer.prototype.getClassName = function () {
            return "HighlightLayer";
        };
        /**
         * Serializes this Highlight layer
         * @returns a serialized Highlight layer object
         */
        HighlightLayer.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.HighlightLayer";
            // Highlighted meshes
            serializationObject.meshes = [];
            if (this._meshes) {
                for (var m in this._meshes) {
                    var mesh = this._meshes[m];
                    if (mesh) {
                        serializationObject.meshes.push({
                            glowEmissiveOnly: mesh.glowEmissiveOnly,
                            color: mesh.color.asArray(),
                            meshId: mesh.mesh.id
                        });
                    }
                }
            }
            // Excluded meshes
            serializationObject.excludedMeshes = [];
            if (this._excludedMeshes) {
                for (var e in this._excludedMeshes) {
                    var excludedMesh = this._excludedMeshes[e];
                    if (excludedMesh) {
                        serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
                    }
                }
            }
            return serializationObject;
        };
        /**
         * Creates a Highlight layer from parsed Highlight layer data
         * @param parsedHightlightLayer defines the Highlight layer data
         * @param scene defines the current scene
         * @param rootUrl defines the root URL containing the Highlight layer information
         * @returns a parsed Highlight layer
         */
        HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
            var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
            var index;
            // Excluded meshes
            for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
                var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
                if (mesh) {
                    hl.addExcludedMesh(mesh);
                }
            }
            // Included meshes
            for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
                var highlightedMesh = parsedHightlightLayer.meshes[index];
                var mesh = scene.getMeshByID(highlightedMesh.meshId);
                if (mesh) {
                    hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
                }
            }
            return hl;
        };
        /**
         * Effect Name of the highlight layer.
         */
        HighlightLayer.EffectName = "HighlightLayer";
        /**
         * The neutral color used during the preparation of the glow effect.
         * This is black by default as the blend operation is a blend operation.
         */
        HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
        /**
         * Stencil value used for glowing meshes.
         */
        HighlightLayer.GlowingMeshStencilReference = 0x02;
        /**
         * Stencil value used for the other meshes in the scene.
         */
        HighlightLayer.NormalMeshStencilReference = 0x01;
        __decorate([
            BABYLON.serialize()
        ], HighlightLayer.prototype, "innerGlow", void 0);
        __decorate([
            BABYLON.serialize()
        ], HighlightLayer.prototype, "outerGlow", void 0);
        __decorate([
            BABYLON.serialize()
        ], HighlightLayer.prototype, "blurHorizontalSize", null);
        __decorate([
            BABYLON.serialize()
        ], HighlightLayer.prototype, "blurVerticalSize", null);
        __decorate([
            BABYLON.serialize("options")
        ], HighlightLayer.prototype, "_options", void 0);
        return HighlightLayer;
    }(BABYLON.EffectLayer));
    BABYLON.HighlightLayer = HighlightLayer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.highlightLayer.js.map







var BABYLON;
(function (BABYLON) {
    BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
        for (var index = 0; index < this.effectLayers.length; index++) {
            if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
                return this.effectLayers[index];
            }
        }
        return null;
    };
    /**
     * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
     *
     * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
     * glowy meshes to your scene.
     *
     * Documentation: https://doc.babylonjs.com/how_to/glow_layer
     */
    var GlowLayer = /** @class */ (function (_super) {
        __extends(GlowLayer, _super);
        /**
         * Instantiates a new glow Layer and references it to the scene.
         * @param name The name of the layer
         * @param scene The scene to use the layer in
         * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
         */
        function GlowLayer(name, scene, options) {
            var _this = _super.call(this, name, scene) || this;
            _this._intensity = 1.0;
            _this._includedOnlyMeshes = [];
            _this._excludedMeshes = [];
            _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
            // Adapt options
            _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
            // Initialize the layer
            _this._init({
                alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
                camera: _this._options.camera,
                mainTextureFixedSize: _this._options.mainTextureFixedSize,
                mainTextureRatio: _this._options.mainTextureRatio,
                renderingGroupId: _this._options.renderingGroupId
            });
            return _this;
        }
        Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
            /**
             * Gets the kernel size of the blur.
             */
            get: function () {
                return this._horizontalBlurPostprocess1.kernel;
            },
            /**
             * Sets the kernel size of the blur.
             */
            set: function (value) {
                this._horizontalBlurPostprocess1.kernel = value;
                this._verticalBlurPostprocess1.kernel = value;
                this._horizontalBlurPostprocess2.kernel = value;
                this._verticalBlurPostprocess2.kernel = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(GlowLayer.prototype, "intensity", {
            /**
             * Gets the glow intensity.
             */
            get: function () {
                return this._intensity;
            },
            /**
             * Sets the glow intensity.
             */
            set: function (value) {
                this._intensity = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Get the effect name of the layer.
         * @return The effect name
         */
        GlowLayer.prototype.getEffectName = function () {
            return GlowLayer.EffectName;
        };
        /**
         * Create the merge effect. This is the shader use to blit the information back
         * to the main canvas at the end of the scene rendering.
         */
        GlowLayer.prototype._createMergeEffect = function () {
            // Effect
            return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
        };
        /**
         * Creates the render target textures and post processes used in the glow layer.
         */
        GlowLayer.prototype._createTextureAndPostProcesses = function () {
            var _this = this;
            var blurTextureWidth = this._mainTextureDesiredSize.width;
            var blurTextureHeight = this._mainTextureDesiredSize.height;
            blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
            blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
            var textureType = 0;
            if (this._engine.getCaps().textureHalfFloatRender) {
                textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
            }
            else {
                textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
            }
            this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
                width: blurTextureWidth,
                height: blurTextureHeight
            }, this._scene, false, true, textureType);
            this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._blurTexture1.renderParticles = false;
            this._blurTexture1.ignoreCameraViewport = true;
            var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
            var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
            this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
                width: blurTextureWidth2,
                height: blurTextureHeight2
            }, this._scene, false, true, textureType);
            this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
            this._blurTexture2.renderParticles = false;
            this._blurTexture2.ignoreCameraViewport = true;
            this._textures = [this._blurTexture1, this._blurTexture2];
            this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
                width: blurTextureWidth,
                height: blurTextureHeight
            }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
            this._horizontalBlurPostprocess1.width = blurTextureWidth;
            this._horizontalBlurPostprocess1.height = blurTextureHeight;
            this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
                effect.setTexture("textureSampler", _this._mainTexture);
            });
            this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
                width: blurTextureWidth,
                height: blurTextureHeight
            }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
            this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
                width: blurTextureWidth2,
                height: blurTextureHeight2
            }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
            this._horizontalBlurPostprocess2.width = blurTextureWidth2;
            this._horizontalBlurPostprocess2.height = blurTextureHeight2;
            this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
                effect.setTexture("textureSampler", _this._blurTexture1);
            });
            this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
                width: blurTextureWidth2,
                height: blurTextureHeight2
            }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
            this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
            this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
            this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
            this._mainTexture.samples = this._options.mainTextureSamples;
            this._mainTexture.onAfterUnbindObservable.add(function () {
                var internalTexture = _this._blurTexture1.getInternalTexture();
                if (internalTexture) {
                    _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
                    internalTexture = _this._blurTexture2.getInternalTexture();
                    if (internalTexture) {
                        _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
                    }
                }
            });
            // Prevent autoClear.
            this._postProcesses.map(function (pp) { pp.autoClear = false; });
        };
        /**
         * Checks for the readiness of the element composing the layer.
         * @param subMesh the mesh to check for
         * @param useInstances specify wether or not to use instances to render the mesh
         * @param emissiveTexture the associated emissive texture used to generate the glow
         * @return true if ready otherwise, false
         */
        GlowLayer.prototype.isReady = function (subMesh, useInstances) {
            var material = subMesh.getMaterial();
            var mesh = subMesh.getRenderingMesh();
            if (!material || !mesh) {
                return false;
            }
            var emissiveTexture = material.emissiveTexture;
            return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
        };
        /**
         * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
         */
        GlowLayer.prototype.needStencil = function () {
            return false;
        };
        /**
         * Implementation specific of rendering the generating effect on the main canvas.
         * @param effect The effect used to render through
         */
        GlowLayer.prototype._internalRender = function (effect) {
            // Texture
            effect.setTexture("textureSampler", this._blurTexture1);
            effect.setTexture("textureSampler2", this._blurTexture2);
            effect.setFloat("offset", this._intensity);
            // Cache
            var engine = this._engine;
            var previousStencilBuffer = engine.getStencilBuffer();
            // Draw order
            engine.setStencilBuffer(false);
            engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
            // Draw order
            engine.setStencilBuffer(previousStencilBuffer);
        };
        /**
         * Sets the required values for both the emissive texture and and the main color.
         */
        GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
            var textureLevel = 1.0;
            if (this.customEmissiveTextureSelector) {
                this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
            }
            else {
                if (material) {
                    this._emissiveTextureAndColor.texture = material.emissiveTexture;
                    if (this._emissiveTextureAndColor.texture) {
                        textureLevel = this._emissiveTextureAndColor.texture.level;
                    }
                }
                else {
                    this._emissiveTextureAndColor.texture = null;
                }
            }
            if (this.customEmissiveColorSelector) {
                this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
            }
            else {
                if (material.emissiveColor) {
                    this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
                }
                else {
                    this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
                }
            }
        };
        /**
         * Returns true if the mesh should render, otherwise false.
         * @param mesh The mesh to render
         * @returns true if it should render otherwise false
         */
        GlowLayer.prototype._shouldRenderMesh = function (mesh) {
            return this.hasMesh(mesh);
        };
        /**
         * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
         * @param mesh The mesh to exclude from the glow layer
         */
        GlowLayer.prototype.addExcludedMesh = function (mesh) {
            if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
                this._excludedMeshes.push(mesh.uniqueId);
            }
        };
        /**
          * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
          * @param mesh The mesh to remove
          */
        GlowLayer.prototype.removeExcludedMesh = function (mesh) {
            var index = this._excludedMeshes.indexOf(mesh.uniqueId);
            if (index !== -1) {
                this._excludedMeshes.splice(index, 1);
            }
        };
        /**
         * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
         * @param mesh The mesh to include in the glow layer
         */
        GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
            if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
                this._includedOnlyMeshes.push(mesh.uniqueId);
            }
        };
        /**
          * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
          * @param mesh The mesh to remove
          */
        GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
            var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
            if (index !== -1) {
                this._includedOnlyMeshes.splice(index, 1);
            }
        };
        /**
         * Determine if a given mesh will be used in the glow layer
         * @param mesh The mesh to test
         * @returns true if the mesh will be highlighted by the current glow layer
         */
        GlowLayer.prototype.hasMesh = function (mesh) {
            if (!_super.prototype.hasMesh.call(this, mesh)) {
                return false;
            }
            // Included Mesh
            if (this._includedOnlyMeshes.length) {
                return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
            }
            // Excluded Mesh
            if (this._excludedMeshes.length) {
                return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
            }
            return true;
        };
        /**
         * Free any resources and references associated to a mesh.
         * Internal use
         * @param mesh The mesh to free.
         * @hidden
         */
        GlowLayer.prototype._disposeMesh = function (mesh) {
            this.removeIncludedOnlyMesh(mesh);
            this.removeExcludedMesh(mesh);
        };
        /**
          * Gets the class name of the effect layer
          * @returns the string with the class name of the effect layer
          */
        GlowLayer.prototype.getClassName = function () {
            return "GlowLayer";
        };
        /**
         * Serializes this glow layer
         * @returns a serialized glow layer object
         */
        GlowLayer.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.GlowLayer";
            var index;
            // Included meshes
            serializationObject.includedMeshes = [];
            if (this._includedOnlyMeshes.length) {
                for (index = 0; index < this._includedOnlyMeshes.length; index++) {
                    var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
                    if (mesh) {
                        serializationObject.includedMeshes.push(mesh.id);
                    }
                }
            }
            // Excluded meshes
            serializationObject.excludedMeshes = [];
            if (this._excludedMeshes.length) {
                for (index = 0; index < this._excludedMeshes.length; index++) {
                    var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
                    if (mesh) {
                        serializationObject.excludedMeshes.push(mesh.id);
                    }
                }
            }
            return serializationObject;
        };
        /**
         * Creates a Glow Layer from parsed glow layer data
         * @param parsedGlowLayer defines glow layer data
         * @param scene defines the current scene
         * @param rootUrl defines the root URL containing the glow layer information
         * @returns a parsed Glow Layer
         */
        GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
            var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
            var index;
            // Excluded meshes
            for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
                var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
                if (mesh) {
                    gl.addExcludedMesh(mesh);
                }
            }
            // Included meshes
            for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
                var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
                if (mesh) {
                    gl.addIncludedOnlyMesh(mesh);
                }
            }
            return gl;
        };
        /**
         * Effect Name of the layer.
         */
        GlowLayer.EffectName = "GlowLayer";
        /**
         * The default blur kernel size used for the glow.
         */
        GlowLayer.DefaultBlurKernelSize = 32;
        /**
         * The default texture size ratio used for the glow.
         */
        GlowLayer.DefaultTextureRatio = 0.5;
        __decorate([
            BABYLON.serialize()
        ], GlowLayer.prototype, "blurKernelSize", null);
        __decorate([
            BABYLON.serialize()
        ], GlowLayer.prototype, "intensity", null);
        __decorate([
            BABYLON.serialize("options")
        ], GlowLayer.prototype, "_options", void 0);
        return GlowLayer;
    }(BABYLON.EffectLayer));
    BABYLON.GlowLayer = GlowLayer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.glowLayer.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Defines the list of states available for a task inside a AssetsManager
     */
    var AssetTaskState;
    (function (AssetTaskState) {
        /**
         * Initialization
         */
        AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
        /**
         * Running
         */
        AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
        /**
         * Done
         */
        AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
        /**
         * Error
         */
        AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
    })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
    /**
     * Define an abstract asset task used with a AssetsManager class to load assets into a scene
     */
    var AbstractAssetTask = /** @class */ (function () {
        /**
         * Creates a new AssetsManager
         * @param name defines the name of the task
         */
        function AbstractAssetTask(
        /**
         * Task name
         */ name) {
            this.name = name;
            this._isCompleted = false;
            this._taskState = AssetTaskState.INIT;
        }
        Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
            /**
             * Get if the task is completed
             */
            get: function () {
                return this._isCompleted;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
            /**
             * Gets the current state of the task
             */
            get: function () {
                return this._taskState;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
            /**
             * Gets the current error object (if task is in error)
             */
            get: function () {
                return this._errorObject;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Internal only
         * @hidden
         */
        AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
            if (this._errorObject) {
                return;
            }
            this._errorObject = {
                message: message,
                exception: exception
            };
        };
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var _this = this;
            this._taskState = AssetTaskState.RUNNING;
            this.runTask(scene, function () {
                _this.onDoneCallback(onSuccess, onError);
            }, function (msg, exception) {
                _this.onErrorCallback(onError, msg, exception);
            });
        };
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            throw new Error("runTask is not implemented");
        };
        /**
         * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
         * This can be used with failed tasks that have the reason for failure fixed.
         */
        AbstractAssetTask.prototype.reset = function () {
            this._taskState = AssetTaskState.INIT;
        };
        AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
            this._taskState = AssetTaskState.ERROR;
            this._errorObject = {
                message: message,
                exception: exception
            };
            if (this.onError) {
                this.onError(this, message, exception);
            }
            onError();
        };
        AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
            try {
                this._taskState = AssetTaskState.DONE;
                this._isCompleted = true;
                if (this.onSuccess) {
                    this.onSuccess(this);
                }
                onSuccess();
            }
            catch (e) {
                this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
            }
        };
        return AbstractAssetTask;
    }());
    BABYLON.AbstractAssetTask = AbstractAssetTask;
    /**
     * Class used to share progress information about assets loading
     */
    var AssetsProgressEvent = /** @class */ (function () {
        /**
         * Creates a AssetsProgressEvent
         * @param remainingCount defines the number of remaining tasks to process
         * @param totalCount defines the total number of tasks
         * @param task defines the task that was just processed
         */
        function AssetsProgressEvent(remainingCount, totalCount, task) {
            this.remainingCount = remainingCount;
            this.totalCount = totalCount;
            this.task = task;
        }
        return AssetsProgressEvent;
    }());
    BABYLON.AssetsProgressEvent = AssetsProgressEvent;
    /**
     * Define a task used by AssetsManager to load meshes
     */
    var MeshAssetTask = /** @class */ (function (_super) {
        __extends(MeshAssetTask, _super);
        /**
         * Creates a new MeshAssetTask
         * @param name defines the name of the task
         * @param meshesNames defines the list of mesh's names you want to load
         * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
         * @param sceneFilename defines the filename of the scene to load from
         */
        function MeshAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the list of mesh's names you want to load
         */
        meshesNames, 
        /**
         * Defines the root url to use as a base to load your meshes and associated resources
         */
        rootUrl, 
        /**
         * Defines the filename of the scene to load from
         */
        sceneFilename) {
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.meshesNames = meshesNames;
            _this.rootUrl = rootUrl;
            _this.sceneFilename = sceneFilename;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            var _this = this;
            BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
                _this.loadedMeshes = meshes;
                _this.loadedParticleSystems = particleSystems;
                _this.loadedSkeletons = skeletons;
                onSuccess();
            }, null, function (scene, message, exception) {
                onError(message, exception);
            });
        };
        return MeshAssetTask;
    }(AbstractAssetTask));
    BABYLON.MeshAssetTask = MeshAssetTask;
    /**
     * Define a task used by AssetsManager to load text content
     */
    var TextFileAssetTask = /** @class */ (function (_super) {
        __extends(TextFileAssetTask, _super);
        /**
         * Creates a new TextFileAssetTask object
         * @param name defines the name of the task
         * @param url defines the location of the file to load
         */
        function TextFileAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the location of the file to load
         */
        url) {
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.url = url;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            var _this = this;
            scene._loadFile(this.url, function (data) {
                _this.text = data;
                onSuccess();
            }, undefined, false, false, function (request, exception) {
                if (request) {
                    onError(request.status + " " + request.statusText, exception);
                }
            });
        };
        return TextFileAssetTask;
    }(AbstractAssetTask));
    BABYLON.TextFileAssetTask = TextFileAssetTask;
    /**
     * Define a task used by AssetsManager to load binary data
     */
    var BinaryFileAssetTask = /** @class */ (function (_super) {
        __extends(BinaryFileAssetTask, _super);
        /**
         * Creates a new BinaryFileAssetTask object
         * @param name defines the name of the new task
         * @param url defines the location of the file to load
         */
        function BinaryFileAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the location of the file to load
         */
        url) {
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.url = url;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            var _this = this;
            scene._loadFile(this.url, function (data) {
                _this.data = data;
                onSuccess();
            }, undefined, true, true, function (request, exception) {
                if (request) {
                    onError(request.status + " " + request.statusText, exception);
                }
            });
        };
        return BinaryFileAssetTask;
    }(AbstractAssetTask));
    BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
    /**
     * Define a task used by AssetsManager to load images
     */
    var ImageAssetTask = /** @class */ (function (_super) {
        __extends(ImageAssetTask, _super);
        /**
         * Creates a new ImageAssetTask
         * @param name defines the name of the task
         * @param url defines the location of the image to load
         */
        function ImageAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the location of the image to load
         */
        url) {
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.url = url;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            var _this = this;
            var img = new Image();
            BABYLON.Tools.SetCorsBehavior(this.url, img);
            img.onload = function () {
                _this.image = img;
                onSuccess();
            };
            img.onerror = function (err) {
                onError("Error loading image", err);
            };
            img.src = this.url;
        };
        return ImageAssetTask;
    }(AbstractAssetTask));
    BABYLON.ImageAssetTask = ImageAssetTask;
    /**
     * Define a task used by AssetsManager to load 2D textures
     */
    var TextureAssetTask = /** @class */ (function (_super) {
        __extends(TextureAssetTask, _super);
        /**
         * Creates a new TextureAssetTask object
         * @param name defines the name of the task
         * @param url defines the location of the file to load
         * @param noMipmap defines if mipmap should not be generated (default is false)
         * @param invertY defines if texture must be inverted on Y axis (default is false)
         * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
         */
        function TextureAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the location of the file to load
         */
        url, 
        /**
         * Defines if mipmap should not be generated (default is false)
         */
        noMipmap, 
        /**
         * Defines if texture must be inverted on Y axis (default is false)
         */
        invertY, 
        /**
         * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
         */
        samplingMode) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.url = url;
            _this.noMipmap = noMipmap;
            _this.invertY = invertY;
            _this.samplingMode = samplingMode;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            var onload = function () {
                onSuccess();
            };
            var onerror = function (message, exception) {
                onError(message, exception);
            };
            this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
        };
        return TextureAssetTask;
    }(AbstractAssetTask));
    BABYLON.TextureAssetTask = TextureAssetTask;
    /**
     * Define a task used by AssetsManager to load cube textures
     */
    var CubeTextureAssetTask = /** @class */ (function (_super) {
        __extends(CubeTextureAssetTask, _super);
        /**
         * Creates a new CubeTextureAssetTask
         * @param name defines the name of the task
         * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
         * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
         * @param noMipmap defines if mipmaps should not be generated (default is false)
         * @param files defines the explicit list of files (undefined by default)
         */
        function CubeTextureAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
         */
        url, 
        /**
         * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
         */
        extensions, 
        /**
         * Defines if mipmaps should not be generated (default is false)
         */
        noMipmap, 
        /**
         * Defines the explicit list of files (undefined by default)
         */
        files) {
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.url = url;
            _this.extensions = extensions;
            _this.noMipmap = noMipmap;
            _this.files = files;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
            var onload = function () {
                onSuccess();
            };
            var onerror = function (message, exception) {
                onError(message, exception);
            };
            this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
        };
        return CubeTextureAssetTask;
    }(AbstractAssetTask));
    BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
    /**
     * Define a task used by AssetsManager to load HDR cube textures
     */
    var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
        __extends(HDRCubeTextureAssetTask, _super);
        /**
         * Creates a new HDRCubeTextureAssetTask object
         * @param name defines the name of the task
         * @param url defines the location of the file to load
         * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
         * @param noMipmap defines if mipmaps should not be generated (default is false)
         * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
         * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
         * @param reserved Internal use only
         */
        function HDRCubeTextureAssetTask(
        /**
         * Defines the name of the task
         */
        name, 
        /**
         * Defines the location of the file to load
         */
        url, 
        /**
         * Defines the desired size (the more it increases the longer the generation will be)
         */
        size, 
        /**
         * Defines if mipmaps should not be generated (default is false)
         */
        noMipmap, 
        /**
         * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
         */
        generateHarmonics, 
        /**
         * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
         */
        gammaSpace, 
        /**
         * Internal Use Only
         */
        reserved) {
            if (noMipmap === void 0) { noMipmap = false; }
            if (generateHarmonics === void 0) { generateHarmonics = true; }
            if (gammaSpace === void 0) { gammaSpace = false; }
            if (reserved === void 0) { reserved = false; }
            var _this = _super.call(this, name) || this;
            _this.name = name;
            _this.url = url;
            _this.size = size;
            _this.noMipmap = noMipmap;
            _this.generateHarmonics = generateHarmonics;
            _this.gammaSpace = gammaSpace;
            _this.reserved = reserved;
            return _this;
        }
        /**
         * Execute the current task
         * @param scene defines the scene where you want your assets to be loaded
         * @param onSuccess is a callback called when the task is successfully executed
         * @param onError is a callback called if an error occurs
         */
        HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
            var onload = function () {
                onSuccess();
            };
            var onerror = function (message, exception) {
                onError(message, exception);
            };
            this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
        };
        return HDRCubeTextureAssetTask;
    }(AbstractAssetTask));
    BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
    /**
     * This class can be used to easily import assets into a scene
     * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
     */
    var AssetsManager = /** @class */ (function () {
        /**
         * Creates a new AssetsManager
         * @param scene defines the scene to work on
         */
        function AssetsManager(scene) {
            this._isLoading = false;
            this._tasks = new Array();
            this._waitingTasksCount = 0;
            this._totalTasksCount = 0;
            /**
             * Observable called when all tasks are processed
             */
            this.onTaskSuccessObservable = new BABYLON.Observable();
            /**
             * Observable called when a task had an error
             */
            this.onTaskErrorObservable = new BABYLON.Observable();
            /**
             * Observable called when a task is successful
             */
            this.onTasksDoneObservable = new BABYLON.Observable();
            /**
             * Observable called when a task is done (whatever the result is)
             */
            this.onProgressObservable = new BABYLON.Observable();
            /**
             * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
             * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
             */
            this.useDefaultLoadingScreen = true;
            this._scene = scene;
        }
        /**
         * Add a MeshAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param meshesNames defines the name of meshes to load
         * @param rootUrl defines the root url to use to locate files
         * @param sceneFilename defines the filename of the scene file
         * @returns a new MeshAssetTask object
         */
        AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
            var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
            this._tasks.push(task);
            return task;
        };
        /**
         * Add a TextFileAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param url defines the url of the file to load
         * @returns a new TextFileAssetTask object
         */
        AssetsManager.prototype.addTextFileTask = function (taskName, url) {
            var task = new TextFileAssetTask(taskName, url);
            this._tasks.push(task);
            return task;
        };
        /**
         * Add a BinaryFileAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param url defines the url of the file to load
         * @returns a new BinaryFileAssetTask object
         */
        AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
            var task = new BinaryFileAssetTask(taskName, url);
            this._tasks.push(task);
            return task;
        };
        /**
         * Add a ImageAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param url defines the url of the file to load
         * @returns a new ImageAssetTask object
         */
        AssetsManager.prototype.addImageTask = function (taskName, url) {
            var task = new ImageAssetTask(taskName, url);
            this._tasks.push(task);
            return task;
        };
        /**
         * Add a TextureAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param url defines the url of the file to load
         * @param noMipmap defines if the texture must not receive mipmaps (false by default)
         * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
         * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
         * @returns a new TextureAssetTask object
         */
        AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
            this._tasks.push(task);
            return task;
        };
        /**
         * Add a CubeTextureAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param url defines the url of the file to load
         * @param extensions defines the extension to use to load the cube map (can be null)
         * @param noMipmap defines if the texture must not receive mipmaps (false by default)
         * @param files defines the list of files to load (can be null)
         * @returns a new CubeTextureAssetTask object
         */
        AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
            var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
            this._tasks.push(task);
            return task;
        };
        /**
         *
         * Add a HDRCubeTextureAssetTask to the list of active tasks
         * @param taskName defines the name of the new task
         * @param url defines the url of the file to load
         * @param size defines the size you want for the cubemap (can be null)
         * @param noMipmap defines if the texture must not receive mipmaps (false by default)
         * @param generateHarmonics defines if you want to automatically generate (true by default)
         * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
         * @param reserved Internal use only
         * @returns a new HDRCubeTextureAssetTask object
         */
        AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
            if (noMipmap === void 0) { noMipmap = false; }
            if (generateHarmonics === void 0) { generateHarmonics = true; }
            if (gammaSpace === void 0) { gammaSpace = false; }
            if (reserved === void 0) { reserved = false; }
            var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
            this._tasks.push(task);
            return task;
        };
        /**
         * Remove a task from the assets manager.
         * @param task the task to remove
         */
        AssetsManager.prototype.removeTask = function (task) {
            var index = this._tasks.indexOf(task);
            if (index > -1) {
                this._tasks.splice(index, 1);
            }
        };
        AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
            this._waitingTasksCount--;
            try {
                if (this.onProgress) {
                    this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
                }
                this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
            }
            catch (e) {
                BABYLON.Tools.Error("Error running progress callbacks.");
                console.log(e);
            }
            if (this._waitingTasksCount === 0) {
                try {
                    if (this.onFinish) {
                        this.onFinish(this._tasks);
                    }
                    // Let's remove successfull tasks
                    var currentTasks = this._tasks.slice();
                    for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
                        var task = currentTasks_1[_i];
                        if (task.taskState === AssetTaskState.DONE) {
                            var index = this._tasks.indexOf(task);
                            if (index > -1) {
                                this._tasks.splice(index, 1);
                            }
                        }
                    }
                    this.onTasksDoneObservable.notifyObservers(this._tasks);
                }
                catch (e) {
                    BABYLON.Tools.Error("Error running tasks-done callbacks.");
                    console.log(e);
                }
                this._isLoading = false;
                this._scene.getEngine().hideLoadingUI();
            }
        };
        AssetsManager.prototype._runTask = function (task) {
            var _this = this;
            var done = function () {
                try {
                    if (_this.onTaskSuccess) {
                        _this.onTaskSuccess(task);
                    }
                    _this.onTaskSuccessObservable.notifyObservers(task);
                    _this._decreaseWaitingTasksCount(task);
                }
                catch (e) {
                    error("Error executing task success callbacks", e);
                }
            };
            var error = function (message, exception) {
                task._setErrorObject(message, exception);
                if (_this.onTaskError) {
                    _this.onTaskError(task);
                }
                _this.onTaskErrorObservable.notifyObservers(task);
                _this._decreaseWaitingTasksCount(task);
            };
            task.run(this._scene, done, error);
        };
        /**
         * Reset the AssetsManager and remove all tasks
         * @return the current instance of the AssetsManager
         */
        AssetsManager.prototype.reset = function () {
            this._isLoading = false;
            this._tasks = new Array();
            return this;
        };
        /**
         * Start the loading process
         * @return the current instance of the AssetsManager
         */
        AssetsManager.prototype.load = function () {
            if (this._isLoading) {
                return this;
            }
            this._isLoading = true;
            this._waitingTasksCount = this._tasks.length;
            this._totalTasksCount = this._tasks.length;
            if (this._waitingTasksCount === 0) {
                this._isLoading = false;
                if (this.onFinish) {
                    this.onFinish(this._tasks);
                }
                this.onTasksDoneObservable.notifyObservers(this._tasks);
                return this;
            }
            if (this.useDefaultLoadingScreen) {
                this._scene.getEngine().displayLoadingUI();
            }
            for (var index = 0; index < this._tasks.length; index++) {
                var task = this._tasks[index];
                if (task.taskState === AssetTaskState.INIT) {
                    this._runTask(task);
                }
            }
            return this;
        };
        return AssetsManager;
    }());
    BABYLON.AssetsManager = AssetsManager;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.assetsManager.js.map

var BABYLON;
(function (BABYLON) {
    var serializedGeometries = [];
    var serializeGeometry = function (geometry, serializationGeometries) {
        if (serializedGeometries[geometry.id]) {
            return;
        }
        if (geometry.doNotSerialize) {
            return;
        }
        if (geometry instanceof BABYLON.BoxGeometry) {
            serializationGeometries.boxes.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.SphereGeometry) {
            serializationGeometries.spheres.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.CylinderGeometry) {
            serializationGeometries.cylinders.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.TorusGeometry) {
            serializationGeometries.toruses.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.GroundGeometry) {
            serializationGeometries.grounds.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.Plane) {
            serializationGeometries.planes.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON.TorusKnotGeometry) {
            serializationGeometries.torusKnots.push(geometry.serialize());
        }
        else if (geometry instanceof BABYLON._PrimitiveGeometry) {
            throw new Error("Unknown primitive type");
        }
        else {
            serializationGeometries.vertexData.push(geometry.serializeVerticeData());
        }
        serializedGeometries[geometry.id] = true;
    };
    var serializeMesh = function (mesh, serializationScene) {
        var serializationObject = {};
        // Geometry
        var geometry = mesh._geometry;
        if (geometry) {
            if (!mesh.getScene().getGeometryByID(geometry.id)) {
                // 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);
            }
        }
        // Custom
        if (mesh.serialize) {
            mesh.serialize(serializationObject);
        }
        return serializationObject;
    };
    var finalizeSingleMesh = function (mesh, serializationObject) {
        //only works if the mesh is already loaded
        if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
            //serialize material
            if (mesh.material) {
                if (mesh.material instanceof BABYLON.MultiMaterial) {
                    serializationObject.multiMaterials = serializationObject.multiMaterials || [];
                    serializationObject.materials = serializationObject.materials || [];
                    if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
                        serializationObject.multiMaterials.push(mesh.material.serialize());
                        var _loop_1 = function (submaterial) {
                            if (submaterial) {
                                if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
                                    serializationObject.materials.push(submaterial.serialize());
                                }
                            }
                        };
                        for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
                            var submaterial = _a[_i];
                            _loop_1(submaterial);
                        }
                    }
                }
                else {
                    serializationObject.materials = serializationObject.materials || [];
                    if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
                        serializationObject.materials.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));
        }
    };
    /**
     * Class used to serialize a scene into a string
     */
    var SceneSerializer = /** @class */ (function () {
        function SceneSerializer() {
        }
        /**
         * Clear cache used by a previous serialization
         */
        SceneSerializer.ClearCache = function () {
            serializedGeometries = [];
        };
        /**
         * Serialize a scene into a JSON compatible object
         * @param scene defines the scene to serialize
         * @returns a JSON compatible object
         */
        SceneSerializer.Serialize = function (scene) {
            var serializationObject = {};
            SceneSerializer.ClearCache();
            // 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()) {
                var physicEngine = scene.getPhysicsEngine();
                if (physicEngine) {
                    serializationObject.physicsEnabled = true;
                    serializationObject.physicsGravity = physicEngine.gravity.asArray();
                    serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
                }
            }
            // Metadata
            if (scene.metadata) {
                serializationObject.metadata = scene.metadata;
            }
            // Morph targets
            serializationObject.morphTargetManagers = [];
            for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
                var abstractMesh = _a[_i];
                var manager = abstractMesh.morphTargetManager;
                if (manager) {
                    serializationObject.morphTargetManagers.push(manager.serialize());
                }
            }
            // Lights
            serializationObject.lights = [];
            var index;
            var light;
            for (index = 0; index < scene.lights.length; index++) {
                light = scene.lights[index];
                if (!light.doNotSerialize) {
                    serializationObject.lights.push(light.serialize());
                }
            }
            // Cameras
            serializationObject.cameras = [];
            for (index = 0; index < scene.cameras.length; index++) {
                var camera = scene.cameras[index];
                if (!camera.doNotSerialize) {
                    serializationObject.cameras.push(camera.serialize());
                }
            }
            if (scene.activeCamera) {
                serializationObject.activeCameraID = scene.activeCamera.id;
            }
            // Animations
            BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
            // Materials
            serializationObject.materials = [];
            serializationObject.multiMaterials = [];
            var material;
            for (index = 0; index < scene.materials.length; index++) {
                material = scene.materials[index];
                if (!material.doNotSerialize) {
                    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());
            }
            // Environment texture
            if (scene.environmentTexture) {
                serializationObject.environmentTexture = scene.environmentTexture.name;
            }
            // Skeletons
            serializationObject.skeletons = [];
            for (index = 0; index < scene.skeletons.length; index++) {
                var skeleton = scene.skeletons[index];
                if (!skeleton.doNotSerialize) {
                    serializationObject.skeletons.push(skeleton.serialize());
                }
            }
            // Transform nodes
            serializationObject.transformNodes = [];
            for (index = 0; index < scene.transformNodes.length; index++) {
                serializationObject.transformNodes.push(scene.transformNodes[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 BABYLON.Mesh) {
                    var mesh = abstractMesh;
                    if (!mesh.doNotSerialize) {
                        if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.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());
            }
            // Action Manager
            if (scene.actionManager) {
                serializationObject.actions = scene.actionManager.serialize("scene");
            }
            // Components
            for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
                var component = _c[_b];
                component.serialize(serializationObject);
            }
            return serializationObject;
        };
        /**
         * Serialize a mesh into a JSON compatible object
         * @param toSerialize defines the mesh to serialize
         * @param withParents defines if parents must be serialized as well
         * @param withChildren defines if children must be serialized as well
         * @returns a JSON compatible object
         */
        SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
            if (withParents === void 0) { withParents = false; }
            if (withChildren === void 0) { withChildren = false; }
            var serializationObject = {};
            SceneSerializer.ClearCache();
            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(function (node) {
                            if (node instanceof BABYLON.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(function (mesh) {
                finalizeSingleMesh(mesh, serializationObject);
            });
            return serializationObject;
        };
        return SceneSerializer;
    }());
    BABYLON.SceneSerializer = SceneSerializer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sceneSerializer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to generate realtime reflection / refraction cube textures
     * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
     */
    var ReflectionProbe = /** @class */ (function () {
        /**
         * Creates a new reflection probe
         * @param name defines the name of the probe
         * @param size defines the texture resolution (for each face)
         * @param scene defines the hosting scene
         * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
         * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
         */
        function ReflectionProbe(
        /** defines the name of the probe */
        name, size, scene, generateMipMaps, useFloat) {
            if (generateMipMaps === void 0) { generateMipMaps = true; }
            if (useFloat === void 0) { useFloat = false; }
            var _this = this;
            this.name = name;
            this._viewMatrix = BABYLON.Matrix.Identity();
            this._target = BABYLON.Vector3.Zero();
            this._add = BABYLON.Vector3.Zero();
            this._invertYAxis = false;
            /** Gets or sets probe position (center of the cube map) */
            this.position = BABYLON.Vector3.Zero();
            this._scene = scene;
            // Create the scene field if not exist.
            if (!this._scene.reflectionProbes) {
                this._scene.reflectionProbes = new Array();
            }
            this._scene.reflectionProbes.push(this);
            this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
            this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
                switch (faceIndex) {
                    case 0:
                        _this._add.copyFromFloats(1, 0, 0);
                        break;
                    case 1:
                        _this._add.copyFromFloats(-1, 0, 0);
                        break;
                    case 2:
                        _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
                        break;
                    case 3:
                        _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
                        break;
                    case 4:
                        _this._add.copyFromFloats(0, 0, 1);
                        break;
                    case 5:
                        _this._add.copyFromFloats(0, 0, -1);
                        break;
                }
                if (_this._attachedMesh) {
                    _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
                }
                _this.position.addToRef(_this._add, _this._target);
                BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
                scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
                scene._forcedViewPosition = _this.position;
            });
            this._renderTargetTexture.onAfterUnbindObservable.add(function () {
                scene._forcedViewPosition = null;
                scene.updateTransformMatrix(true);
            });
            if (scene.activeCamera) {
                this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
            }
        }
        Object.defineProperty(ReflectionProbe.prototype, "samples", {
            /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
            get: function () {
                return this._renderTargetTexture.samples;
            },
            set: function (value) {
                this._renderTargetTexture.samples = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
            /** Gets or sets the refresh rate to use (on every frame by default) */
            get: function () {
                return this._renderTargetTexture.refreshRate;
            },
            set: function (value) {
                this._renderTargetTexture.refreshRate = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Gets the hosting scene
         * @returns a Scene
         */
        ReflectionProbe.prototype.getScene = function () {
            return this._scene;
        };
        Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
            /** Gets the internal CubeTexture used to render to */
            get: function () {
                return this._renderTargetTexture;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(ReflectionProbe.prototype, "renderList", {
            /** Gets the list of meshes to render */
            get: function () {
                return this._renderTargetTexture.renderList;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
         * @param mesh defines the mesh to attach to
         */
        ReflectionProbe.prototype.attachToMesh = function (mesh) {
            this._attachedMesh = mesh;
        };
        /**
         * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
         * @param renderingGroupId The rendering group id corresponding to its index
         * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
         */
        ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
            this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
        };
        /**
         * Clean all associated resources
         */
        ReflectionProbe.prototype.dispose = function () {
            var index = this._scene.reflectionProbes.indexOf(this);
            if (index !== -1) {
                // Remove from the scene if found
                this._scene.reflectionProbes.splice(index, 1);
            }
            if (this._renderTargetTexture) {
                this._renderTargetTexture.dispose();
                this._renderTargetTexture = null;
            }
        };
        return ReflectionProbe;
    }());
    BABYLON.ReflectionProbe = ReflectionProbe;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.reflectionProbe.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Defines the layer scene component responsible to manage any layers
     * in a given scene.
     */
    var LayerSceneComponent = /** @class */ (function () {
        /**
         * Creates a new instance of the component for the given scene
         * @param scene Defines the scene to register the component in
         */
        function LayerSceneComponent(scene) {
            /**
             * The component name helpfull to identify the component in the list of scene components.
             */
            this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
            this.scene = scene;
            this._engine = scene.getEngine();
            scene.layers = new Array();
        }
        /**
         * Registers the component in a given scene
         */
        LayerSceneComponent.prototype.register = function () {
            this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
            this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
        };
        /**
         * Rebuilds the elements related to this component in case of
         * context lost for instance.
         */
        LayerSceneComponent.prototype.rebuild = function () {
            var layers = this.scene.layers;
            for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
                var layer = layers_1[_i];
                layer._rebuild();
            }
        };
        /**
         * Disposes the component and the associated ressources.
         */
        LayerSceneComponent.prototype.dispose = function () {
            var layers = this.scene.layers;
            while (layers.length) {
                layers[0].dispose();
            }
        };
        LayerSceneComponent.prototype._draw = function (camera, isBackground) {
            var layers = this.scene.layers;
            if (layers.length) {
                this._engine.setDepthBuffer(false);
                var cameraLayerMask = camera.layerMask;
                for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
                    var layer = layers_2[_i];
                    if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
                        layer.render();
                    }
                }
                this._engine.setDepthBuffer(true);
            }
        };
        LayerSceneComponent.prototype._drawBackground = function (camera) {
            this._draw(camera, true);
        };
        LayerSceneComponent.prototype._drawForeground = function (camera) {
            this._draw(camera, false);
        };
        return LayerSceneComponent;
    }());
    BABYLON.LayerSceneComponent = LayerSceneComponent;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.layerSceneComponent.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This represents a full screen 2d layer.
     * This can be usefull to display a picture in the  background of your scene for instance.
     * @see https://www.babylonjs-playground.com/#08A2BS#1
     */
    var Layer = /** @class */ (function () {
        /**
         * Instantiates a new layer.
         * This represents a full screen 2d layer.
         * This can be usefull to display a picture in the  background of your scene for instance.
         * @see https://www.babylonjs-playground.com/#08A2BS#1
         * @param name Define the name of the layer in the scene
         * @param imgUrl Define the url of the texture to display in the layer
         * @param scene Define the scene the layer belongs to
         * @param isBackground Defines whether the layer is displayed in front or behind the scene
         * @param color Defines a color for the layer
         */
        function Layer(
        /**
         * Define the name of the layer.
         */
        name, imgUrl, scene, isBackground, color) {
            this.name = name;
            /**
             * Define the scale of the layer in order to zoom in out of the texture.
             */
            this.scale = new BABYLON.Vector2(1, 1);
            /**
             * Define an offset for the layer in order to shift the texture.
             */
            this.offset = new BABYLON.Vector2(0, 0);
            /**
             * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
             */
            this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
            /**
             * Define a mask to restrict the layer to only some of the scene cameras.
             */
            this.layerMask = 0x0FFFFFFF;
            this._vertexBuffers = {};
            /**
             * An event triggered when the layer is disposed.
             */
            this.onDisposeObservable = new BABYLON.Observable();
            /**
            * An event triggered before rendering the scene
            */
            this.onBeforeRenderObservable = new BABYLON.Observable();
            /**
            * An event triggered after rendering the scene
            */
            this.onAfterRenderObservable = new BABYLON.Observable();
            this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
            this.isBackground = isBackground === undefined ? true : isBackground;
            this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
            this._scene = (scene || BABYLON.Engine.LastCreatedScene);
            var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
            if (!layerComponent) {
                layerComponent = new BABYLON.LayerSceneComponent(this._scene);
                this._scene._addComponent(layerComponent);
            }
            this._scene.layers.push(this);
            var engine = this._scene.getEngine();
            // VBO
            var vertices = [];
            vertices.push(1, 1);
            vertices.push(-1, 1);
            vertices.push(-1, -1);
            vertices.push(1, -1);
            var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
            this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
            this._createIndexBuffer();
            // Effects
            this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
            this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
        }
        Object.defineProperty(Layer.prototype, "onDispose", {
            /**
             * Back compatibility with callback before the onDisposeObservable existed.
             * The set callback will be triggered when the layer has been disposed.
             */
            set: function (callback) {
                if (this._onDisposeObserver) {
                    this.onDisposeObservable.remove(this._onDisposeObserver);
                }
                this._onDisposeObserver = this.onDisposeObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Layer.prototype, "onBeforeRender", {
            /**
             * Back compatibility with callback before the onBeforeRenderObservable existed.
             * The set callback will be triggered just before rendering the layer.
             */
            set: function (callback) {
                if (this._onBeforeRenderObserver) {
                    this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
                }
                this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(Layer.prototype, "onAfterRender", {
            /**
             * Back compatibility with callback before the onAfterRenderObservable existed.
             * The set callback will be triggered just after rendering the layer.
             */
            set: function (callback) {
                if (this._onAfterRenderObserver) {
                    this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
                }
                this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
            },
            enumerable: true,
            configurable: true
        });
        Layer.prototype._createIndexBuffer = function () {
            var engine = this._scene.getEngine();
            // Indices
            var indices = [];
            indices.push(0);
            indices.push(1);
            indices.push(2);
            indices.push(0);
            indices.push(2);
            indices.push(3);
            this._indexBuffer = engine.createIndexBuffer(indices);
        };
        /** @hidden */
        Layer.prototype._rebuild = function () {
            var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vb) {
                vb._rebuild();
            }
            this._createIndexBuffer();
        };
        /**
         * Renders the layer in the scene.
         */
        Layer.prototype.render = function () {
            var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
            // Check
            if (!currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
                return;
            }
            var engine = this._scene.getEngine();
            this.onBeforeRenderObservable.notifyObservers(this);
            // Render
            engine.enableEffect(currentEffect);
            engine.setState(false);
            // Texture
            currentEffect.setTexture("textureSampler", this.texture);
            currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
            // Color
            currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
            // Scale / offset
            currentEffect.setVector2("offset", this.offset);
            currentEffect.setVector2("scale", this.scale);
            // VBOs
            engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
            // Draw order
            if (!this.alphaTest) {
                engine.setAlphaMode(this.alphaBlendingMode);
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
                engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
            }
            else {
                engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
            }
            this.onAfterRenderObservable.notifyObservers(this);
        };
        /**
         * Disposes and releases the associated ressources.
         */
        Layer.prototype.dispose = function () {
            var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
            if (vertexBuffer) {
                vertexBuffer.dispose();
                this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
            }
            if (this._indexBuffer) {
                this._scene.getEngine()._releaseBuffer(this._indexBuffer);
                this._indexBuffer = null;
            }
            if (this.texture) {
                this.texture.dispose();
                this.texture = null;
            }
            // Remove from scene
            var index = this._scene.layers.indexOf(this);
            this._scene.layers.splice(index, 1);
            // Callback
            this.onDisposeObservable.notifyObservers(this);
            this.onDisposeObservable.clear();
            this.onAfterRenderObservable.clear();
            this.onBeforeRenderObservable.clear();
        };
        return Layer;
    }());
    BABYLON.Layer = Layer;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.layer.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Class used to host texture specific utilities
     */
    var TextureTools = /** @class */ (function () {
        function TextureTools() {
        }
        /**
         * Uses the GPU to create a copy texture rescaled at a given size
         * @param texture Texture to copy from
         * @param width defines the desired width
         * @param height defines the desired height
         * @param useBilinearMode defines if bilinear mode has to be used
         * @return the generated texture
         */
        TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
            if (useBilinearMode === void 0) { useBilinearMode = true; }
            var scene = texture.getScene();
            var engine = scene.getEngine();
            var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
            rtt.wrapU = texture.wrapU;
            rtt.wrapV = texture.wrapV;
            rtt.uOffset = texture.uOffset;
            rtt.vOffset = texture.vOffset;
            rtt.uScale = texture.uScale;
            rtt.vScale = texture.vScale;
            rtt.uAng = texture.uAng;
            rtt.vAng = texture.vAng;
            rtt.wAng = texture.wAng;
            rtt.coordinatesIndex = texture.coordinatesIndex;
            rtt.level = texture.level;
            rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
            rtt._texture.isReady = false;
            texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
            texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
            var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
            passPostProcess.getEffect().executeWhenCompiled(function () {
                passPostProcess.onApply = function (effect) {
                    effect.setTexture("textureSampler", texture);
                };
                var internalTexture = rtt.getInternalTexture();
                if (internalTexture) {
                    scene.postProcessManager.directRender([passPostProcess], internalTexture);
                    engine.unBindFramebuffer(internalTexture);
                    rtt.disposeFramebufferObjects();
                    passPostProcess.dispose();
                    internalTexture.isReady = true;
                }
            });
            return rtt;
        };
        /**
         * Gets an environment BRDF texture for a given scene
         * @param scene defines the hosting scene
         * @returns the environment BRDF texture
         */
        TextureTools.GetEnvironmentBRDFTexture = function (scene) {
            if (!scene._environmentBRDFTexture) {
                var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
                texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                scene._environmentBRDFTexture = texture;
            }
            return scene._environmentBRDFTexture;
        };
        TextureTools._environmentBRDFBase64Texture = "data:image/png;base64, ";
        return TextureTools;
    }());
    BABYLON.TextureTools = TextureTools;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.textureTools.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * The framing behavior (BABYLON.FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane.
     * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
     */
    var FramingBehavior = /** @class */ (function () {
        function FramingBehavior() {
            this._mode = FramingBehavior.FitFrustumSidesMode;
            this._radiusScale = 1.0;
            this._positionScale = 0.5;
            this._defaultElevation = 0.3;
            this._elevationReturnTime = 1500;
            this._elevationReturnWaitTime = 1000;
            this._zoomStopsAnimation = false;
            this._framingTime = 1500;
            /**
             * Define if the behavior should automatically change the configured
             * camera limits and sensibilities.
             */
            this.autoCorrectCameraLimitsAndSensibility = true;
            this._isPointerDown = false;
            this._lastInteractionTime = -Infinity;
            // Framing control
            this._animatables = new Array();
            this._betaIsAnimating = false;
        }
        Object.defineProperty(FramingBehavior.prototype, "name", {
            /**
             * Gets the name of the behavior.
             */
            get: function () {
                return "Framing";
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "mode", {
            /**
             * Gets current mode used by the behavior.
             */
            get: function () {
                return this._mode;
            },
            /**
             * Sets the current mode used by the behavior
             */
            set: function (mode) {
                this._mode = mode;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
            /**
             * Gets the scale applied to the radius
             */
            get: function () {
                return this._radiusScale;
            },
            /**
             * Sets the scale applied to the radius (1 by default)
             */
            set: function (radius) {
                this._radiusScale = radius;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "positionScale", {
            /**
             * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
             */
            get: function () {
                return this._positionScale;
            },
            /**
             * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
             */
            set: function (scale) {
                this._positionScale = scale;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
            /**
            * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
            * behaviour is triggered, in radians.
            */
            get: function () {
                return this._defaultElevation;
            },
            /**
            * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
            * behaviour is triggered, in radians.
            */
            set: function (elevation) {
                this._defaultElevation = elevation;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
            /**
             * Gets the time (in milliseconds) taken to return to the default beta position.
             * Negative value indicates camera should not return to default.
             */
            get: function () {
                return this._elevationReturnTime;
            },
            /**
             * Sets the time (in milliseconds) taken to return to the default beta position.
             * Negative value indicates camera should not return to default.
             */
            set: function (speed) {
                this._elevationReturnTime = speed;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
            /**
             * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
             */
            get: function () {
                return this._elevationReturnWaitTime;
            },
            /**
             * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
             */
            set: function (time) {
                this._elevationReturnWaitTime = time;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
            /**
            * Gets the flag that indicates if user zooming should stop animation.
            */
            get: function () {
                return this._zoomStopsAnimation;
            },
            /**
            * Sets the flag that indicates if user zooming should stop animation.
            */
            set: function (flag) {
                this._zoomStopsAnimation = flag;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(FramingBehavior.prototype, "framingTime", {
            /**
             * Gets the transition time when framing the mesh, in milliseconds
            */
            get: function () {
                return this._framingTime;
            },
            /**
             * Sets the transition time when framing the mesh, in milliseconds
            */
            set: function (time) {
                this._framingTime = time;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Initializes the behavior.
         */
        FramingBehavior.prototype.init = function () {
            // Do notihng
        };
        /**
         * Attaches the behavior to its arc rotate camera.
         * @param camera Defines the camera to attach the behavior to
         */
        FramingBehavior.prototype.attach = function (camera) {
            var _this = this;
            this._attachedCamera = camera;
            var scene = this._attachedCamera.getScene();
            FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
            this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
                if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                    _this._isPointerDown = true;
                    return;
                }
                if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
                    _this._isPointerDown = false;
                }
            });
            this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
                if (mesh) {
                    _this.zoomOnMesh(mesh);
                }
            });
            this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
                // Stop the animation if there is user interaction and the animation should stop for this interaction
                _this._applyUserInteraction();
                // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
                // back to the default position after a given timeout
                _this._maintainCameraAboveGround();
            });
        };
        /**
         * Detaches the behavior from its current arc rotate camera.
         */
        FramingBehavior.prototype.detach = function () {
            if (!this._attachedCamera) {
                return;
            }
            var scene = this._attachedCamera.getScene();
            if (this._onPrePointerObservableObserver) {
                scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
            }
            if (this._onAfterCheckInputsObserver) {
                this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
            }
            if (this._onMeshTargetChangedObserver) {
                this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
            }
            this._attachedCamera = null;
        };
        /**
         * Targets the given mesh and updates zoom level accordingly.
         * @param mesh  The mesh to target.
         * @param radius Optional. If a cached radius position already exists, overrides default.
         * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
         * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
         * @param onAnimationEnd Callback triggered at the end of the framing animation
         */
        FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
            if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
            if (onAnimationEnd === void 0) { onAnimationEnd = null; }
            mesh.computeWorldMatrix(true);
            var boundingBox = mesh.getBoundingInfo().boundingBox;
            this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
        };
        /**
         * Targets the given mesh with its children and updates zoom level accordingly.
         * @param mesh  The mesh to target.
         * @param radius Optional. If a cached radius position already exists, overrides default.
         * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
         * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
         * @param onAnimationEnd Callback triggered at the end of the framing animation
         */
        FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
            if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
            if (onAnimationEnd === void 0) { onAnimationEnd = null; }
            mesh.computeWorldMatrix(true);
            var boundingBox = mesh.getHierarchyBoundingVectors(true);
            this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
        };
        /**
         * Targets the given meshes with their children and updates zoom level accordingly.
         * @param meshes  The mesh to target.
         * @param radius Optional. If a cached radius position already exists, overrides default.
         * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
         * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
         * @param onAnimationEnd Callback triggered at the end of the framing animation
         */
        FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
            if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
            if (onAnimationEnd === void 0) { onAnimationEnd = null; }
            var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
            var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
            for (var i = 0; i < meshes.length; i++) {
                var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
                BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
                BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
            }
            this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
        };
        /**
         * Targets the bounding box info defined by its extends and updates zoom level accordingly.
         * @param minimumWorld Determines the smaller position of the bounding box extend
         * @param maximumWorld Determines the bigger position of the bounding box extend
         * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
         * @param onAnimationEnd Callback triggered at the end of the framing animation
         */
        FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
            var _this = this;
            if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
            if (onAnimationEnd === void 0) { onAnimationEnd = null; }
            var zoomTarget;
            if (!this._attachedCamera) {
                return;
            }
            // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
            var bottom = minimumWorld.y;
            var top = maximumWorld.y;
            var zoomTargetY = bottom + (top - bottom) * this._positionScale;
            var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
            if (focusOnOriginXZ) {
                zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
            }
            else {
                var centerWorld = minimumWorld.add(radiusWorld);
                zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
            }
            if (!this._vectorTransition) {
                this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
            }
            this._betaIsAnimating = true;
            var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
            if (animatable) {
                this._animatables.push(animatable);
            }
            // sets the radius and lower radius bounds
            // Small delta ensures camera is not always at lower zoom limit.
            var radius = 0;
            if (this._mode === FramingBehavior.FitFrustumSidesMode) {
                var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
                if (this.autoCorrectCameraLimitsAndSensibility) {
                    this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
                }
                radius = position;
            }
            else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
                radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
                if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
                    this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
                }
            }
            // Set sensibilities
            if (this.autoCorrectCameraLimitsAndSensibility) {
                var extend = maximumWorld.subtract(minimumWorld).length();
                this._attachedCamera.panningSensibility = 5000 / extend;
                this._attachedCamera.wheelPrecision = 100 / radius;
            }
            // transition to new radius
            if (!this._radiusTransition) {
                this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
            }
            animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
                _this.stopAllAnimations();
                if (onAnimationEnd) {
                    onAnimationEnd();
                }
                if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
                    _this._attachedCamera.storeState();
                }
            });
            if (animatable) {
                this._animatables.push(animatable);
            }
        };
        /**
         * Calculates the lowest radius for the camera based on the bounding box of the mesh.
         * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
         *			  frustum width.
         * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
         *		 to fully enclose the mesh in the viewing frustum.
         */
        FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
            var size = maximumWorld.subtract(minimumWorld);
            var boxVectorGlobalDiagonal = size.length();
            var frustumSlope = this._getFrustumSlope();
            // Formula for setting distance
            // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
            var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
            // Horizon distance
            var radius = radiusWithoutFraming * this._radiusScale;
            var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
            var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
            var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
            var camera = this._attachedCamera;
            if (!camera) {
                return 0;
            }
            if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
                // Don't exceed the requested limit
                distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
            }
            // Don't exceed the upper radius limit
            if (camera.upperRadiusLimit) {
                distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
            }
            return distance;
        };
        /**
         * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
         * is automatically returned to its default position (expected to be above ground plane).
         */
        FramingBehavior.prototype._maintainCameraAboveGround = function () {
            var _this = this;
            if (this._elevationReturnTime < 0) {
                return;
            }
            var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
            var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
            var limitBeta = Math.PI * 0.5;
            // Bring the camera back up if below the ground plane
            if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
                this._betaIsAnimating = true;
                //Transition to new position
                this.stopAllAnimations();
                if (!this._betaTransition) {
                    this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
                }
                var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
                    _this._clearAnimationLocks();
                    _this.stopAllAnimations();
                });
                if (animatabe) {
                    this._animatables.push(animatabe);
                }
            }
        };
        /**
         * Returns the frustum slope based on the canvas ratio and camera FOV
         * @returns The frustum slope represented as a Vector2 with X and Y slopes
         */
        FramingBehavior.prototype._getFrustumSlope = function () {
            // Calculate the viewport ratio
            // Aspect Ratio is Height/Width.
            var camera = this._attachedCamera;
            if (!camera) {
                return BABYLON.Vector2.Zero();
            }
            var engine = camera.getScene().getEngine();
            var aspectRatio = engine.getAspectRatio(camera);
            // Camera FOV is the vertical field of view (top-bottom) in radians.
            // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
            var frustumSlopeY = Math.tan(camera.fov / 2);
            // Slope of the frustum left/right planes in view space, relative to the forward vector.
            // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
            // along the forward vector.
            var frustumSlopeX = frustumSlopeY * aspectRatio;
            return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
        };
        /**
         * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
         */
        FramingBehavior.prototype._clearAnimationLocks = function () {
            this._betaIsAnimating = false;
        };
        /**
         *  Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
         */
        FramingBehavior.prototype._applyUserInteraction = function () {
            if (this.isUserIsMoving) {
                this._lastInteractionTime = BABYLON.Tools.Now;
                this.stopAllAnimations();
                this._clearAnimationLocks();
            }
        };
        /**
         * Stops and removes all animations that have been applied to the camera
         */
        FramingBehavior.prototype.stopAllAnimations = function () {
            if (this._attachedCamera) {
                this._attachedCamera.animations = [];
            }
            while (this._animatables.length) {
                if (this._animatables[0]) {
                    this._animatables[0].onAnimationEnd = null;
                    this._animatables[0].stop();
                }
                this._animatables.shift();
            }
        };
        Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
            /**
             * Gets a value indicating if the user is moving the camera
             */
            get: function () {
                if (!this._attachedCamera) {
                    return false;
                }
                return this._attachedCamera.inertialAlphaOffset !== 0 ||
                    this._attachedCamera.inertialBetaOffset !== 0 ||
                    this._attachedCamera.inertialRadiusOffset !== 0 ||
                    this._attachedCamera.inertialPanningX !== 0 ||
                    this._attachedCamera.inertialPanningY !== 0 ||
                    this._isPointerDown;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * The easing function used by animations
         */
        FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
        /**
         * The easing mode used by animations
         */
        FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
        // Statics
        /**
         * The camera can move all the way towards the mesh.
         */
        FramingBehavior.IgnoreBoundsSizeMode = 0;
        /**
         * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
         */
        FramingBehavior.FitFrustumSidesMode = 1;
        return FramingBehavior;
    }());
    BABYLON.FramingBehavior = FramingBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.framingBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
     * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
     */
    var BouncingBehavior = /** @class */ (function () {
        function BouncingBehavior() {
            /**
             * The duration of the animation, in milliseconds
             */
            this.transitionDuration = 450;
            /**
             * Length of the distance animated by the transition when lower radius is reached
             */
            this.lowerRadiusTransitionRange = 2;
            /**
             * Length of the distance animated by the transition when upper radius is reached
             */
            this.upperRadiusTransitionRange = -2;
            this._autoTransitionRange = false;
            // Animations
            this._radiusIsAnimating = false;
            this._radiusBounceTransition = null;
            this._animatables = new Array();
        }
        Object.defineProperty(BouncingBehavior.prototype, "name", {
            /**
             * Gets the name of the behavior.
             */
            get: function () {
                return "Bouncing";
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
            /**
             * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
             */
            get: function () {
                return this._autoTransitionRange;
            },
            /**
             * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
             * Transition ranges will be set to 5% of the bounding box diagonal in world space
             */
            set: function (value) {
                var _this = this;
                if (this._autoTransitionRange === value) {
                    return;
                }
                this._autoTransitionRange = value;
                var camera = this._attachedCamera;
                if (!camera) {
                    return;
                }
                if (value) {
                    this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
                        if (!mesh) {
                            return;
                        }
                        mesh.computeWorldMatrix(true);
                        var diagonal = mesh.getBoundingInfo().diagonalLength;
                        _this.lowerRadiusTransitionRange = diagonal * 0.05;
                        _this.upperRadiusTransitionRange = diagonal * 0.05;
                    });
                }
                else if (this._onMeshTargetChangedObserver) {
                    camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Initializes the behavior.
         */
        BouncingBehavior.prototype.init = function () {
            // Do notihng
        };
        /**
         * Attaches the behavior to its arc rotate camera.
         * @param camera Defines the camera to attach the behavior to
         */
        BouncingBehavior.prototype.attach = function (camera) {
            var _this = this;
            this._attachedCamera = camera;
            this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
                if (!_this._attachedCamera) {
                    return;
                }
                // Add the bounce animation to the lower radius limit
                if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
                    _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
                }
                // Add the bounce animation to the upper radius limit
                if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
                    _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
                }
            });
        };
        /**
         * Detaches the behavior from its current arc rotate camera.
         */
        BouncingBehavior.prototype.detach = function () {
            if (!this._attachedCamera) {
                return;
            }
            if (this._onAfterCheckInputsObserver) {
                this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
            }
            if (this._onMeshTargetChangedObserver) {
                this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
            }
            this._attachedCamera = null;
        };
        /**
         * Checks if the camera radius is at the specified limit. Takes into account animation locks.
         * @param radiusLimit The limit to check against.
         * @return Bool to indicate if at limit.
         */
        BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
            if (!this._attachedCamera) {
                return false;
            }
            if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
                return true;
            }
            return false;
        };
        /**
         * Applies an animation to the radius of the camera, extending by the radiusDelta.
         * @param radiusDelta The delta by which to animate to. Can be negative.
         */
        BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
            var _this = this;
            if (!this._attachedCamera) {
                return;
            }
            if (!this._radiusBounceTransition) {
                BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
                this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
            }
            // Prevent zoom until bounce has completed
            this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
            this._attachedCamera.wheelPrecision = Infinity;
            this._attachedCamera.inertialRadiusOffset = 0;
            // Animate to the radius limit
            this.stopAllAnimations();
            this._radiusIsAnimating = true;
            var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
            if (animatable) {
                this._animatables.push(animatable);
            }
        };
        /**
         * Removes all animation locks. Allows new animations to be added to any of the camera properties.
         */
        BouncingBehavior.prototype._clearAnimationLocks = function () {
            this._radiusIsAnimating = false;
            if (this._attachedCamera) {
                this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
            }
        };
        /**
         * Stops and removes all animations that have been applied to the camera
         */
        BouncingBehavior.prototype.stopAllAnimations = function () {
            if (this._attachedCamera) {
                this._attachedCamera.animations = [];
            }
            while (this._animatables.length) {
                this._animatables[0].onAnimationEnd = null;
                this._animatables[0].stop();
                this._animatables.shift();
            }
        };
        /**
         * The easing function used by animations
         */
        BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
        /**
         * The easing mode used by animations
         */
        BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
        return BouncingBehavior;
    }());
    BABYLON.BouncingBehavior = BouncingBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.bouncingBehavior.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
     * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
     */
    var AutoRotationBehavior = /** @class */ (function () {
        function AutoRotationBehavior() {
            this._zoomStopsAnimation = false;
            this._idleRotationSpeed = 0.05;
            this._idleRotationWaitTime = 2000;
            this._idleRotationSpinupTime = 2000;
            this._isPointerDown = false;
            this._lastFrameTime = null;
            this._lastInteractionTime = -Infinity;
            this._cameraRotationSpeed = 0;
            this._lastFrameRadius = 0;
        }
        Object.defineProperty(AutoRotationBehavior.prototype, "name", {
            /**
             * Gets the name of the behavior.
             */
            get: function () {
                return "AutoRotation";
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
            /**
            * Gets the flag that indicates if user zooming should stop animation.
            */
            get: function () {
                return this._zoomStopsAnimation;
            },
            /**
            * Sets the flag that indicates if user zooming should stop animation.
            */
            set: function (flag) {
                this._zoomStopsAnimation = flag;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
            /**
            * Gets the default speed at which the camera rotates around the model.
            */
            get: function () {
                return this._idleRotationSpeed;
            },
            /**
            * Sets the default speed at which the camera rotates around the model.
            */
            set: function (speed) {
                this._idleRotationSpeed = speed;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
            /**
            * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
            */
            get: function () {
                return this._idleRotationWaitTime;
            },
            /**
            * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
            */
            set: function (time) {
                this._idleRotationWaitTime = time;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
            /**
            * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
            */
            get: function () {
                return this._idleRotationSpinupTime;
            },
            /**
            * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
            */
            set: function (time) {
                this._idleRotationSpinupTime = time;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
            /**
             * Gets a value indicating if the camera is currently rotating because of this behavior
             */
            get: function () {
                return Math.abs(this._cameraRotationSpeed) > 0;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Initializes the behavior.
         */
        AutoRotationBehavior.prototype.init = function () {
            // Do notihng
        };
        /**
         * Attaches the behavior to its arc rotate camera.
         * @param camera Defines the camera to attach the behavior to
         */
        AutoRotationBehavior.prototype.attach = function (camera) {
            var _this = this;
            this._attachedCamera = camera;
            var scene = this._attachedCamera.getScene();
            this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
                if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
                    _this._isPointerDown = true;
                    return;
                }
                if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
                    _this._isPointerDown = false;
                }
            });
            this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
                var now = BABYLON.Tools.Now;
                var dt = 0;
                if (_this._lastFrameTime != null) {
                    dt = now - _this._lastFrameTime;
                }
                _this._lastFrameTime = now;
                // Stop the animation if there is user interaction and the animation should stop for this interaction
                _this._applyUserInteraction();
                var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
                var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
                _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
                // Step camera rotation by rotation speed
                if (_this._attachedCamera) {
                    _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
                }
            });
        };
        /**
         * Detaches the behavior from its current arc rotate camera.
         */
        AutoRotationBehavior.prototype.detach = function () {
            if (!this._attachedCamera) {
                return;
            }
            var scene = this._attachedCamera.getScene();
            if (this._onPrePointerObservableObserver) {
                scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
            }
            this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
            this._attachedCamera = null;
        };
        /**
         * Returns true if user is scrolling.
         * @return true if user is scrolling.
         */
        AutoRotationBehavior.prototype._userIsZooming = function () {
            if (!this._attachedCamera) {
                return false;
            }
            return this._attachedCamera.inertialRadiusOffset !== 0;
        };
        AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
            if (!this._attachedCamera) {
                return false;
            }
            var zoomHasHitLimit = false;
            if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
                zoomHasHitLimit = true;
            }
            // Update the record of previous radius - works as an approx. indicator of hitting radius limits
            this._lastFrameRadius = this._attachedCamera.radius;
            return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
        };
        /**
         *  Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
         */
        AutoRotationBehavior.prototype._applyUserInteraction = function () {
            if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
                this._lastInteractionTime = BABYLON.Tools.Now;
            }
        };
        // Tools
        AutoRotationBehavior.prototype._userIsMoving = function () {
            if (!this._attachedCamera) {
                return false;
            }
            return this._attachedCamera.inertialAlphaOffset !== 0 ||
                this._attachedCamera.inertialBetaOffset !== 0 ||
                this._attachedCamera.inertialRadiusOffset !== 0 ||
                this._attachedCamera.inertialPanningX !== 0 ||
                this._attachedCamera.inertialPanningY !== 0 ||
                this._isPointerDown;
        };
        return AutoRotationBehavior;
    }());
    BABYLON.AutoRotationBehavior = AutoRotationBehavior;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.autoRotationBehavior.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Options to create the null engine
     */
    var NullEngineOptions = /** @class */ (function () {
        function NullEngineOptions() {
            /**
             * Render width (Default: 512)
             */
            this.renderWidth = 512;
            /**
             * Render height (Default: 256)
             */
            this.renderHeight = 256;
            /**
             * Texture size (Default: 512)
             */
            this.textureSize = 512;
            /**
             * If delta time between frames should be constant
             * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
             */
            this.deterministicLockstep = false;
            /**
             * Maximum about of steps between frames (Default: 4)
             * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
             */
            this.lockstepMaxSteps = 4;
        }
        return NullEngineOptions;
    }());
    BABYLON.NullEngineOptions = NullEngineOptions;
    /**
     * The null engine class provides support for headless version of babylon.js.
     * This can be used in server side scenario or for testing purposes
     */
    var NullEngine = /** @class */ (function (_super) {
        __extends(NullEngine, _super);
        function NullEngine(options) {
            if (options === void 0) { options = new NullEngineOptions(); }
            var _this = _super.call(this, null) || this;
            if (options.deterministicLockstep === undefined) {
                options.deterministicLockstep = false;
            }
            if (options.lockstepMaxSteps === undefined) {
                options.lockstepMaxSteps = 4;
            }
            _this._options = options;
            // Init caps
            // We consider we are on a webgl1 capable device
            _this._caps = new BABYLON.EngineCapabilities();
            _this._caps.maxTexturesImageUnits = 16;
            _this._caps.maxVertexTextureImageUnits = 16;
            _this._caps.maxTextureSize = 512;
            _this._caps.maxCubemapTextureSize = 512;
            _this._caps.maxRenderTextureSize = 512;
            _this._caps.maxVertexAttribs = 16;
            _this._caps.maxVaryingVectors = 16;
            _this._caps.maxFragmentUniformVectors = 16;
            _this._caps.maxVertexUniformVectors = 16;
            // Extensions
            _this._caps.standardDerivatives = false;
            _this._caps.astc = null;
            _this._caps.s3tc = null;
            _this._caps.pvrtc = null;
            _this._caps.etc1 = null;
            _this._caps.etc2 = null;
            _this._caps.textureAnisotropicFilterExtension = null;
            _this._caps.maxAnisotropy = 0;
            _this._caps.uintIndices = false;
            _this._caps.fragmentDepthSupported = false;
            _this._caps.highPrecisionShaderSupported = true;
            _this._caps.colorBufferFloat = false;
            _this._caps.textureFloat = false;
            _this._caps.textureFloatLinearFiltering = false;
            _this._caps.textureFloatRender = false;
            _this._caps.textureHalfFloat = false;
            _this._caps.textureHalfFloatLinearFiltering = false;
            _this._caps.textureHalfFloatRender = false;
            _this._caps.textureLOD = false;
            _this._caps.drawBuffersExtension = false;
            _this._caps.depthTextureExtension = false;
            _this._caps.vertexArrayObject = false;
            _this._caps.instancedArrays = false;
            BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
            // Wrappers
            if (typeof URL === "undefined") {
                URL = {
                    createObjectURL: function () { },
                    revokeObjectURL: function () { }
                };
            }
            if (typeof Blob === "undefined") {
                Blob = function () { };
            }
            return _this;
        }
        /**
         * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
         */
        NullEngine.prototype.isDeterministicLockStep = function () {
            return this._options.deterministicLockstep;
        };
        /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
        NullEngine.prototype.getLockstepMaxSteps = function () {
            return this._options.lockstepMaxSteps;
        };
        /**
         * Sets hardware scaling, used to save performance if needed
         * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
         */
        NullEngine.prototype.getHardwareScalingLevel = function () {
            return 1.0;
        };
        NullEngine.prototype.createVertexBuffer = function (vertices) {
            return {
                capacity: 0,
                references: 1,
                is32Bits: false
            };
        };
        NullEngine.prototype.createIndexBuffer = function (indices) {
            return {
                capacity: 0,
                references: 1,
                is32Bits: false
            };
        };
        NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
            if (stencil === void 0) { stencil = false; }
        };
        NullEngine.prototype.getRenderWidth = function (useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            if (!useScreen && this._currentRenderTarget) {
                return this._currentRenderTarget.width;
            }
            return this._options.renderWidth;
        };
        NullEngine.prototype.getRenderHeight = function (useScreen) {
            if (useScreen === void 0) { useScreen = false; }
            if (!useScreen && this._currentRenderTarget) {
                return this._currentRenderTarget.height;
            }
            return this._options.renderHeight;
        };
        NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
            this._cachedViewport = viewport;
        };
        NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
            return {
                transformFeedback: null,
                __SPECTOR_rebuildProgram: null
            };
        };
        NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
            return [];
        };
        NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
            return [];
        };
        NullEngine.prototype.bindSamplers = function (effect) {
            this._currentEffect = null;
        };
        NullEngine.prototype.enableEffect = function (effect) {
            this._currentEffect = effect;
            if (effect.onBind) {
                effect.onBind(effect);
            }
            if (effect._onBindObservable) {
                effect._onBindObservable.notifyObservers(effect);
            }
        };
        NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
            if (zOffset === void 0) { zOffset = 0; }
            if (reverseSide === void 0) { reverseSide = false; }
        };
        NullEngine.prototype.setIntArray = function (uniform, array) {
        };
        NullEngine.prototype.setIntArray2 = function (uniform, array) {
        };
        NullEngine.prototype.setIntArray3 = function (uniform, array) {
        };
        NullEngine.prototype.setIntArray4 = function (uniform, array) {
        };
        NullEngine.prototype.setFloatArray = function (uniform, array) {
        };
        NullEngine.prototype.setFloatArray2 = function (uniform, array) {
        };
        NullEngine.prototype.setFloatArray3 = function (uniform, array) {
        };
        NullEngine.prototype.setFloatArray4 = function (uniform, array) {
        };
        NullEngine.prototype.setArray = function (uniform, array) {
        };
        NullEngine.prototype.setArray2 = function (uniform, array) {
        };
        NullEngine.prototype.setArray3 = function (uniform, array) {
        };
        NullEngine.prototype.setArray4 = function (uniform, array) {
        };
        NullEngine.prototype.setMatrices = function (uniform, matrices) {
        };
        NullEngine.prototype.setMatrix = function (uniform, matrix) {
        };
        NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
        };
        NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
        };
        NullEngine.prototype.setFloat = function (uniform, value) {
        };
        NullEngine.prototype.setFloat2 = function (uniform, x, y) {
        };
        NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
        };
        NullEngine.prototype.setBool = function (uniform, bool) {
        };
        NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
        };
        NullEngine.prototype.setColor3 = function (uniform, color3) {
        };
        NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
        };
        NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
            if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
            if (this._alphaMode === mode) {
                return;
            }
            this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
            if (!noDepthWriteChange) {
                this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
            }
            this._alphaMode = mode;
        };
        NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
        };
        NullEngine.prototype.wipeCaches = function (bruteForce) {
            if (this.preventCacheWipeBetweenFrames) {
                return;
            }
            this.resetTextureCache();
            this._currentEffect = null;
            if (bruteForce) {
                this._currentProgram = null;
                this._stencilState.reset();
                this._depthCullingState.reset();
                this._alphaState.reset();
            }
            this._cachedVertexBuffers = null;
            this._cachedIndexBuffer = null;
            this._cachedEffectForVertexBuffers = null;
        };
        NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
        };
        NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
        };
        NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
        };
        /** @hidden */
        NullEngine.prototype._createTexture = function () {
            return {};
        };
        /** @hidden */
        NullEngine.prototype._releaseTexture = function (texture) {
        };
        NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
            if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
            if (onLoad === void 0) { onLoad = null; }
            if (onError === void 0) { onError = null; }
            if (buffer === void 0) { buffer = null; }
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
            var url = String(urlArg);
            texture.url = url;
            texture.generateMipMaps = !noMipmap;
            texture.samplingMode = samplingMode;
            texture.invertY = invertY;
            texture.baseWidth = this._options.textureSize;
            texture.baseHeight = this._options.textureSize;
            texture.width = this._options.textureSize;
            texture.height = this._options.textureSize;
            if (format) {
                texture.format = format;
            }
            texture.isReady = true;
            if (onLoad) {
                onLoad();
            }
            this._internalTexturesCache.push(texture);
            return texture;
        };
        NullEngine.prototype.createRenderTargetTexture = function (size, options) {
            var fullOptions = new BABYLON.RenderTargetCreationOptions();
            if (options !== undefined && typeof options === "object") {
                fullOptions.generateMipMaps = options.generateMipMaps;
                fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
                fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
                fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
                fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
            }
            else {
                fullOptions.generateMipMaps = options;
                fullOptions.generateDepthBuffer = true;
                fullOptions.generateStencilBuffer = false;
                fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
                fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
            }
            var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
            var width = size.width || size;
            var height = size.height || size;
            texture._depthStencilBuffer = {};
            texture._framebuffer = {};
            texture.baseWidth = width;
            texture.baseHeight = height;
            texture.width = width;
            texture.height = height;
            texture.isReady = true;
            texture.samples = 1;
            texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
            texture.samplingMode = fullOptions.samplingMode;
            texture.type = fullOptions.type;
            texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
            texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
            this._internalTexturesCache.push(texture);
            return texture;
        };
        NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
            texture.samplingMode = samplingMode;
        };
        NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
            if (this._currentRenderTarget) {
                this.unBindFramebuffer(this._currentRenderTarget);
            }
            this._currentRenderTarget = texture;
            this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
            if (this._cachedViewport && !forceFullscreenViewport) {
                this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
            }
        };
        NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
            if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
            this._currentRenderTarget = null;
            if (onBeforeUnbind) {
                if (texture._MSAAFramebuffer) {
                    this._currentFramebuffer = texture._framebuffer;
                }
                onBeforeUnbind();
            }
            this._currentFramebuffer = null;
        };
        NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
            var vbo = {
                capacity: 1,
                references: 1,
                is32Bits: false
            };
            return vbo;
        };
        NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
            if (premulAlpha === void 0) { premulAlpha = false; }
        };
        /**
         * @hidden
         * Get the current error code of the webGL context
         * @returns the error code
         * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
         */
        NullEngine.prototype.getError = function () {
            return 0;
        };
        /** @hidden */
        NullEngine.prototype._getUnpackAlignement = function () {
            return 1;
        };
        /** @hidden */
        NullEngine.prototype._unpackFlipY = function (value) {
        };
        NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
            if (offset === void 0) { offset = 0; }
        };
        /**
         * Updates a dynamic vertex buffer.
         * @param vertexBuffer the vertex buffer to update
         * @param data the data used to update the vertex buffer
         * @param byteOffset the byte offset of the data (optional)
         * @param byteLength the byte length of the data (optional)
         */
        NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
        };
        NullEngine.prototype._bindTextureDirectly = function (target, texture) {
            if (this._boundTexturesCache[this._activeChannel] !== texture) {
                this._boundTexturesCache[this._activeChannel] = texture;
                return true;
            }
            return false;
        };
        /** @hidden */
        NullEngine.prototype._bindTexture = function (channel, texture) {
            if (channel < 0) {
                return;
            }
            this._bindTextureDirectly(0, texture);
        };
        /** @hidden */
        NullEngine.prototype._releaseBuffer = function (buffer) {
            buffer.references--;
            if (buffer.references === 0) {
                return true;
            }
            return false;
        };
        NullEngine.prototype.releaseEffects = function () {
        };
        NullEngine.prototype.displayLoadingUI = function () {
        };
        NullEngine.prototype.hideLoadingUI = function () {
        };
        /** @hidden */
        NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
        };
        /** @hidden */
        NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
        };
        /** @hidden */
        NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
        };
        /** @hidden */
        NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
            if (faceIndex === void 0) { faceIndex = 0; }
            if (lod === void 0) { lod = 0; }
        };
        return NullEngine;
    }(BABYLON.Engine));
    BABYLON.NullEngine = NullEngine;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.nullEngine.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class can be used to get instrumentation data from a Babylon engine
     * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
     */
    var EngineInstrumentation = /** @class */ (function () {
        /**
         * Instantiates a new engine instrumentation.
         * This class can be used to get instrumentation data from a Babylon engine
         * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
         * @param engine Defines the engine to instrument
         */
        function EngineInstrumentation(
        /**
         * Define the instrumented engine.
         */
        engine) {
            this.engine = engine;
            this._captureGPUFrameTime = false;
            this._gpuFrameTime = new BABYLON.PerfCounter();
            this._captureShaderCompilationTime = false;
            this._shaderCompilationTime = new BABYLON.PerfCounter();
            // Observers
            this._onBeginFrameObserver = null;
            this._onEndFrameObserver = null;
            this._onBeforeShaderCompilationObserver = null;
            this._onAfterShaderCompilationObserver = null;
        }
        Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
            // Properties
            /**
             * Gets the perf counter used for GPU frame time
             */
            get: function () {
                return this._gpuFrameTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
            /**
             * Gets the GPU frame time capture status
             */
            get: function () {
                return this._captureGPUFrameTime;
            },
            /**
             * Enable or disable the GPU frame time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureGPUFrameTime) {
                    return;
                }
                this._captureGPUFrameTime = value;
                if (value) {
                    this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
                        if (!_this._gpuFrameTimeToken) {
                            _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
                        }
                    });
                    this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
                        if (!_this._gpuFrameTimeToken) {
                            return;
                        }
                        var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
                        if (time > -1) {
                            _this._gpuFrameTimeToken = null;
                            _this._gpuFrameTime.fetchNewFrame();
                            _this._gpuFrameTime.addCount(time, true);
                        }
                    });
                }
                else {
                    this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
                    this._onBeginFrameObserver = null;
                    this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
                    this._onEndFrameObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
            /**
             * Gets the perf counter used for shader compilation time
             */
            get: function () {
                return this._shaderCompilationTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
            /**
             * Gets the shader compilation time capture status
             */
            get: function () {
                return this._captureShaderCompilationTime;
            },
            /**
             * Enable or disable the shader compilation time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureShaderCompilationTime) {
                    return;
                }
                this._captureShaderCompilationTime = value;
                if (value) {
                    this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
                        _this._shaderCompilationTime.fetchNewFrame();
                        _this._shaderCompilationTime.beginMonitoring();
                    });
                    this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
                        _this._shaderCompilationTime.endMonitoring();
                    });
                }
                else {
                    this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
                    this._onBeforeShaderCompilationObserver = null;
                    this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
                    this._onAfterShaderCompilationObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Dispose and release associated resources.
         */
        EngineInstrumentation.prototype.dispose = function () {
            this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
            this._onBeginFrameObserver = null;
            this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
            this._onEndFrameObserver = null;
            this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
            this._onBeforeShaderCompilationObserver = null;
            this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
            this._onAfterShaderCompilationObserver = null;
            this.engine = null;
        };
        return EngineInstrumentation;
    }());
    BABYLON.EngineInstrumentation = EngineInstrumentation;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.engineInstrumentation.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class can be used to get instrumentation data from a Babylon engine
     * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
     */
    var SceneInstrumentation = /** @class */ (function () {
        /**
         * Instantiates a new scene instrumentation.
         * This class can be used to get instrumentation data from a Babylon engine
         * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
         * @param scene Defines the scene to instrument
         */
        function SceneInstrumentation(
        /**
         * Defines the scene to instrument
         */
        scene) {
            var _this = this;
            this.scene = scene;
            this._captureActiveMeshesEvaluationTime = false;
            this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
            this._captureRenderTargetsRenderTime = false;
            this._renderTargetsRenderTime = new BABYLON.PerfCounter();
            this._captureFrameTime = false;
            this._frameTime = new BABYLON.PerfCounter();
            this._captureRenderTime = false;
            this._renderTime = new BABYLON.PerfCounter();
            this._captureInterFrameTime = false;
            this._interFrameTime = new BABYLON.PerfCounter();
            this._captureParticlesRenderTime = false;
            this._particlesRenderTime = new BABYLON.PerfCounter();
            this._captureSpritesRenderTime = false;
            this._spritesRenderTime = new BABYLON.PerfCounter();
            this._capturePhysicsTime = false;
            this._physicsTime = new BABYLON.PerfCounter();
            this._captureAnimationsTime = false;
            this._animationsTime = new BABYLON.PerfCounter();
            this._captureCameraRenderTime = false;
            this._cameraRenderTime = new BABYLON.PerfCounter();
            // Observers
            this._onBeforeActiveMeshesEvaluationObserver = null;
            this._onAfterActiveMeshesEvaluationObserver = null;
            this._onBeforeRenderTargetsRenderObserver = null;
            this._onAfterRenderTargetsRenderObserver = null;
            this._onAfterRenderObserver = null;
            this._onBeforeDrawPhaseObserver = null;
            this._onAfterDrawPhaseObserver = null;
            this._onBeforeAnimationsObserver = null;
            this._onBeforeParticlesRenderingObserver = null;
            this._onAfterParticlesRenderingObserver = null;
            this._onBeforeSpritesRenderingObserver = null;
            this._onAfterSpritesRenderingObserver = null;
            this._onBeforePhysicsObserver = null;
            this._onAfterPhysicsObserver = null;
            this._onAfterAnimationsObserver = null;
            this._onBeforeCameraRenderObserver = null;
            this._onAfterCameraRenderObserver = null;
            // Before render
            this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
                if (_this._captureActiveMeshesEvaluationTime) {
                    _this._activeMeshesEvaluationTime.fetchNewFrame();
                }
                if (_this._captureRenderTargetsRenderTime) {
                    _this._renderTargetsRenderTime.fetchNewFrame();
                }
                if (_this._captureFrameTime) {
                    BABYLON.Tools.StartPerformanceCounter("Scene rendering");
                    _this._frameTime.beginMonitoring();
                }
                if (_this._captureInterFrameTime) {
                    _this._interFrameTime.endMonitoring();
                }
                if (_this._captureParticlesRenderTime) {
                    _this._particlesRenderTime.fetchNewFrame();
                }
                if (_this._captureSpritesRenderTime) {
                    _this._spritesRenderTime.fetchNewFrame();
                }
                if (_this._captureAnimationsTime) {
                    _this._animationsTime.beginMonitoring();
                }
                _this.scene.getEngine()._drawCalls.fetchNewFrame();
                _this.scene.getEngine()._textureCollisions.fetchNewFrame();
            });
            // After render
            this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
                if (_this._captureFrameTime) {
                    BABYLON.Tools.EndPerformanceCounter("Scene rendering");
                    _this._frameTime.endMonitoring();
                }
                if (_this._captureRenderTime) {
                    _this._renderTime.endMonitoring(false);
                }
                if (_this._captureInterFrameTime) {
                    _this._interFrameTime.beginMonitoring();
                }
            });
        }
        Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
            // Properties
            /**
             * Gets the perf counter used for active meshes evaluation time
             */
            get: function () {
                return this._activeMeshesEvaluationTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
            /**
             * Gets the active meshes evaluation time capture status
             */
            get: function () {
                return this._captureActiveMeshesEvaluationTime;
            },
            /**
             * Enable or disable the active meshes evaluation time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureActiveMeshesEvaluationTime) {
                    return;
                }
                this._captureActiveMeshesEvaluationTime = value;
                if (value) {
                    this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
                        BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
                        _this._activeMeshesEvaluationTime.beginMonitoring();
                    });
                    this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
                        BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
                        _this._activeMeshesEvaluationTime.endMonitoring();
                    });
                }
                else {
                    this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
                    this._onBeforeActiveMeshesEvaluationObserver = null;
                    this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
                    this._onAfterActiveMeshesEvaluationObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
            /**
             * Gets the perf counter used for render targets render time
             */
            get: function () {
                return this._renderTargetsRenderTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
            /**
             * Gets the render targets render time capture status
             */
            get: function () {
                return this._captureRenderTargetsRenderTime;
            },
            /**
             * Enable or disable the render targets render time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureRenderTargetsRenderTime) {
                    return;
                }
                this._captureRenderTargetsRenderTime = value;
                if (value) {
                    this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
                        BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
                        _this._renderTargetsRenderTime.beginMonitoring();
                    });
                    this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
                        BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
                        _this._renderTargetsRenderTime.endMonitoring(false);
                    });
                }
                else {
                    this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
                    this._onBeforeRenderTargetsRenderObserver = null;
                    this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
                    this._onAfterRenderTargetsRenderObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
            /**
             * Gets the perf counter used for particles render time
             */
            get: function () {
                return this._particlesRenderTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
            /**
             * Gets the particles render time capture status
             */
            get: function () {
                return this._captureParticlesRenderTime;
            },
            /**
             * Enable or disable the particles render time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureParticlesRenderTime) {
                    return;
                }
                this._captureParticlesRenderTime = value;
                if (value) {
                    this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
                        BABYLON.Tools.StartPerformanceCounter("Particles");
                        _this._particlesRenderTime.beginMonitoring();
                    });
                    this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
                        BABYLON.Tools.EndPerformanceCounter("Particles");
                        _this._particlesRenderTime.endMonitoring(false);
                    });
                }
                else {
                    this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
                    this._onBeforeParticlesRenderingObserver = null;
                    this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
                    this._onAfterParticlesRenderingObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
            /**
             * Gets the perf counter used for sprites render time
             */
            get: function () {
                return this._spritesRenderTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
            /**
             * Gets the sprites render time capture status
             */
            get: function () {
                return this._captureSpritesRenderTime;
            },
            /**
             * Enable or disable the sprites render time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureSpritesRenderTime) {
                    return;
                }
                this._captureSpritesRenderTime = value;
                if (!this.scene.spriteManagers) {
                    return;
                }
                if (value) {
                    this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
                        BABYLON.Tools.StartPerformanceCounter("Sprites");
                        _this._spritesRenderTime.beginMonitoring();
                    });
                    this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
                        BABYLON.Tools.EndPerformanceCounter("Sprites");
                        _this._spritesRenderTime.endMonitoring(false);
                    });
                }
                else {
                    this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
                    this._onBeforeSpritesRenderingObserver = null;
                    this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
                    this._onAfterSpritesRenderingObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
            /**
             * Gets the perf counter used for physics time
             */
            get: function () {
                return this._physicsTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
            /**
             * Gets the physics time capture status
             */
            get: function () {
                return this._capturePhysicsTime;
            },
            /**
             * Enable or disable the physics time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._capturePhysicsTime) {
                    return;
                }
                if (!this.scene.onBeforePhysicsObservable) {
                    return;
                }
                this._capturePhysicsTime = value;
                if (value) {
                    this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
                        BABYLON.Tools.StartPerformanceCounter("Physics");
                        _this._physicsTime.beginMonitoring();
                    });
                    this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
                        BABYLON.Tools.EndPerformanceCounter("Physics");
                        _this._physicsTime.endMonitoring();
                    });
                }
                else {
                    this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
                    this._onBeforePhysicsObserver = null;
                    this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
                    this._onAfterPhysicsObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
            /**
             * Gets the perf counter used for animations time
             */
            get: function () {
                return this._animationsTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
            /**
             * Gets the animations time capture status
             */
            get: function () {
                return this._captureAnimationsTime;
            },
            /**
             * Enable or disable the animations time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureAnimationsTime) {
                    return;
                }
                this._captureAnimationsTime = value;
                if (value) {
                    this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
                        _this._animationsTime.endMonitoring();
                    });
                }
                else {
                    this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
                    this._onAfterAnimationsObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
            /**
             * Gets the perf counter used for frame time capture
             */
            get: function () {
                return this._frameTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
            /**
             * Gets the frame time capture status
             */
            get: function () {
                return this._captureFrameTime;
            },
            /**
             * Enable or disable the frame time capture
             */
            set: function (value) {
                this._captureFrameTime = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
            /**
             * Gets the perf counter used for inter-frames time capture
             */
            get: function () {
                return this._interFrameTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
            /**
             * Gets the inter-frames time capture status
             */
            get: function () {
                return this._captureInterFrameTime;
            },
            /**
             * Enable or disable the inter-frames time capture
             */
            set: function (value) {
                this._captureInterFrameTime = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
            /**
             * Gets the perf counter used for render time capture
             */
            get: function () {
                return this._renderTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
            /**
             * Gets the render time capture status
             */
            get: function () {
                return this._captureRenderTime;
            },
            /**
             * Enable or disable the render time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureRenderTime) {
                    return;
                }
                this._captureRenderTime = value;
                if (value) {
                    this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
                        _this._renderTime.beginMonitoring();
                        BABYLON.Tools.StartPerformanceCounter("Main render");
                    });
                    this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
                        _this._renderTime.endMonitoring(false);
                        BABYLON.Tools.EndPerformanceCounter("Main render");
                    });
                }
                else {
                    this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
                    this._onBeforeDrawPhaseObserver = null;
                    this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
                    this._onAfterDrawPhaseObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
            /**
             * Gets the perf counter used for camera render time capture
             */
            get: function () {
                return this._cameraRenderTime;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
            /**
             * Gets the camera render time capture status
             */
            get: function () {
                return this._captureCameraRenderTime;
            },
            /**
             * Enable or disable the camera render time capture
             */
            set: function (value) {
                var _this = this;
                if (value === this._captureCameraRenderTime) {
                    return;
                }
                this._captureCameraRenderTime = value;
                if (value) {
                    this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
                        _this._cameraRenderTime.beginMonitoring();
                        BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
                    });
                    this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
                        _this._cameraRenderTime.endMonitoring(false);
                        BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
                    });
                }
                else {
                    this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
                    this._onBeforeCameraRenderObserver = null;
                    this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
                    this._onAfterCameraRenderObserver = null;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
            /**
             * Gets the perf counter used for draw calls
             */
            get: function () {
                return this.scene.getEngine()._drawCalls;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
            /**
             * Gets the perf counter used for texture collisions
             */
            get: function () {
                return this.scene.getEngine()._textureCollisions;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Dispose and release associated resources.
         */
        SceneInstrumentation.prototype.dispose = function () {
            this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
            this._onAfterRenderObserver = null;
            this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
            this._onBeforeActiveMeshesEvaluationObserver = null;
            this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
            this._onAfterActiveMeshesEvaluationObserver = null;
            this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
            this._onBeforeRenderTargetsRenderObserver = null;
            this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
            this._onAfterRenderTargetsRenderObserver = null;
            this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
            this._onBeforeAnimationsObserver = null;
            this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
            this._onBeforeParticlesRenderingObserver = null;
            this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
            this._onAfterParticlesRenderingObserver = null;
            if (this._onBeforeSpritesRenderingObserver) {
                this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
                this._onBeforeSpritesRenderingObserver = null;
            }
            if (this._onAfterSpritesRenderingObserver) {
                this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
                this._onAfterSpritesRenderingObserver = null;
            }
            this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
            this._onBeforeDrawPhaseObserver = null;
            this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
            this._onAfterDrawPhaseObserver = null;
            if (this._onBeforePhysicsObserver) {
                this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
                this._onBeforePhysicsObserver = null;
            }
            if (this._onAfterPhysicsObserver) {
                this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
                this._onAfterPhysicsObserver = null;
            }
            this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
            this._onAfterAnimationsObserver = null;
            this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
            this._onBeforeCameraRenderObserver = null;
            this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
            this._onAfterCameraRenderObserver = null;
            this.scene = null;
        };
        return SceneInstrumentation;
    }());
    BABYLON.SceneInstrumentation = SceneInstrumentation;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sceneInstrumentation.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * @hidden
     **/
    var _TimeToken = /** @class */ (function () {
        function _TimeToken() {
            this._timeElapsedQueryEnded = false;
        }
        return _TimeToken;
    }());
    BABYLON._TimeToken = _TimeToken;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.timeToken.js.map







var BABYLON;
(function (BABYLON) {
    /**
     * Background material defines definition.
     * @hidden Mainly internal Use
     */
    var BackgroundMaterialDefines = /** @class */ (function (_super) {
        __extends(BackgroundMaterialDefines, _super);
        /**
         * Constructor of the defines.
         */
        function BackgroundMaterialDefines() {
            var _this = _super.call(this) || this;
            /**
             * True if the diffuse texture is in use.
             */
            _this.DIFFUSE = false;
            /**
             * The direct UV channel to use.
             */
            _this.DIFFUSEDIRECTUV = 0;
            /**
             * True if the diffuse texture is in gamma space.
             */
            _this.GAMMADIFFUSE = false;
            /**
             * True if the diffuse texture has opacity in the alpha channel.
             */
            _this.DIFFUSEHASALPHA = false;
            /**
             * True if you want the material to fade to transparent at grazing angle.
             */
            _this.OPACITYFRESNEL = false;
            /**
             * True if an extra blur needs to be added in the reflection.
             */
            _this.REFLECTIONBLUR = false;
            /**
             * True if you want the material to fade to reflection at grazing angle.
             */
            _this.REFLECTIONFRESNEL = false;
            /**
             * True if you want the material to falloff as far as you move away from the scene center.
             */
            _this.REFLECTIONFALLOFF = false;
            /**
             * False if the current Webgl implementation does not support the texture lod extension.
             */
            _this.TEXTURELODSUPPORT = false;
            /**
             * True to ensure the data are premultiplied.
             */
            _this.PREMULTIPLYALPHA = false;
            /**
             * True if the texture contains cooked RGB values and not gray scaled multipliers.
             */
            _this.USERGBCOLOR = false;
            /**
             * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
             * stays aligned with the desired configuration.
             */
            _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
            /**
             * True to add noise in order to reduce the banding effect.
             */
            _this.NOISE = false;
            /**
             * is the reflection texture in BGR color scheme?
             * Mainly used to solve a bug in ios10 video tag
             */
            _this.REFLECTIONBGR = false;
            _this.IMAGEPROCESSING = false;
            _this.VIGNETTE = false;
            _this.VIGNETTEBLENDMODEMULTIPLY = false;
            _this.VIGNETTEBLENDMODEOPAQUE = false;
            _this.TONEMAPPING = false;
            _this.TONEMAPPING_ACES = false;
            _this.CONTRAST = false;
            _this.COLORCURVES = false;
            _this.COLORGRADING = false;
            _this.COLORGRADING3D = false;
            _this.SAMPLER3DGREENDEPTH = false;
            _this.SAMPLER3DBGRMAP = false;
            _this.IMAGEPROCESSINGPOSTPROCESS = false;
            _this.EXPOSURE = false;
            // Reflection.
            _this.REFLECTION = false;
            _this.REFLECTIONMAP_3D = false;
            _this.REFLECTIONMAP_SPHERICAL = false;
            _this.REFLECTIONMAP_PLANAR = false;
            _this.REFLECTIONMAP_CUBIC = false;
            _this.REFLECTIONMAP_PROJECTION = false;
            _this.REFLECTIONMAP_SKYBOX = false;
            _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
            _this.REFLECTIONMAP_EXPLICIT = false;
            _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
            _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
            _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
            _this.INVERTCUBICMAP = false;
            _this.REFLECTIONMAP_OPPOSITEZ = false;
            _this.LODINREFLECTIONALPHA = false;
            _this.GAMMAREFLECTION = false;
            _this.RGBDREFLECTION = false;
            _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
            // Default BJS.
            _this.MAINUV1 = false;
            _this.MAINUV2 = false;
            _this.UV1 = false;
            _this.UV2 = false;
            _this.CLIPPLANE = false;
            _this.CLIPPLANE2 = false;
            _this.CLIPPLANE3 = false;
            _this.CLIPPLANE4 = false;
            _this.POINTSIZE = false;
            _this.FOG = false;
            _this.NORMAL = false;
            _this.NUM_BONE_INFLUENCERS = 0;
            _this.BonesPerMesh = 0;
            _this.INSTANCES = false;
            _this.SHADOWFLOAT = false;
            _this.rebuild();
            return _this;
        }
        return BackgroundMaterialDefines;
    }(BABYLON.MaterialDefines));
    /**
     * Background material used to create an efficient environement around your scene.
     */
    var BackgroundMaterial = /** @class */ (function (_super) {
        __extends(BackgroundMaterial, _super);
        /**
         * Instantiates a Background Material in the given scene
         * @param name The friendly name of the material
         * @param scene The scene to add the material to
         */
        function BackgroundMaterial(name, scene) {
            var _this = _super.call(this, name, scene) || this;
            /**
             * Key light Color (multiply against the environement texture)
             */
            _this.primaryColor = BABYLON.Color3.White();
            _this._primaryColorShadowLevel = 0;
            _this._primaryColorHighlightLevel = 0;
            /**
             * Reflection Texture used in the material.
             * Should be author in a specific way for the best result (refer to the documentation).
             */
            _this.reflectionTexture = null;
            /**
             * Reflection Texture level of blur.
             *
             * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
             * texture twice.
             */
            _this.reflectionBlur = 0;
            /**
             * Diffuse Texture used in the material.
             * Should be author in a specific way for the best result (refer to the documentation).
             */
            _this.diffuseTexture = null;
            _this._shadowLights = null;
            /**
             * Specify the list of lights casting shadow on the material.
             * All scene shadow lights will be included if null.
             */
            _this.shadowLights = null;
            /**
             * Helps adjusting the shadow to a softer level if required.
             * 0 means black shadows and 1 means no shadows.
             */
            _this.shadowLevel = 0;
            /**
             * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
             * It is usually zero but might be interesting to modify according to your setup.
             */
            _this.sceneCenter = BABYLON.Vector3.Zero();
            /**
             * This helps specifying that the material is falling off to the sky box at grazing angle.
             * This helps ensuring a nice transition when the camera goes under the ground.
             */
            _this.opacityFresnel = true;
            /**
             * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
             * This helps adding a mirror texture on the ground.
             */
            _this.reflectionFresnel = false;
            /**
             * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
             * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
             */
            _this.reflectionFalloffDistance = 0.0;
            /**
             * This specifies the weight of the reflection against the background in case of reflection Fresnel.
             */
            _this.reflectionAmount = 1.0;
            /**
             * This specifies the weight of the reflection at grazing angle.
             */
            _this.reflectionReflectance0 = 0.05;
            /**
             * This specifies the weight of the reflection at a perpendicular point of view.
             */
            _this.reflectionReflectance90 = 0.5;
            /**
             * Helps to directly use the maps channels instead of their level.
             */
            _this.useRGBColor = true;
            /**
             * This helps reducing the banding effect that could occur on the background.
             */
            _this.enableNoise = false;
            _this._fovMultiplier = 1.0;
            /**
             * Enable the FOV adjustment feature controlled by fovMultiplier.
             */
            _this.useEquirectangularFOV = false;
            _this._maxSimultaneousLights = 4;
            /**
             * Number of Simultaneous lights allowed on the material.
             */
            _this.maxSimultaneousLights = 4;
            /**
             * Keep track of the image processing observer to allow dispose and replace.
             */
            _this._imageProcessingObserver = null;
            /**
             * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
             * Setting this flag to true (not done automatically!) will convert it back to RGB.
             */
            _this.switchToBGR = false;
            // Temp values kept as cache in the material.
            _this._renderTargets = new BABYLON.SmartArray(16);
            _this._reflectionControls = BABYLON.Vector4.Zero();
            _this._white = BABYLON.Color3.White();
            _this._primaryShadowColor = BABYLON.Color3.Black();
            _this._primaryHighlightColor = BABYLON.Color3.Black();
            // Setup the default processing configuration to the scene.
            _this._attachImageProcessingConfiguration(null);
            _this.getRenderTargetTextures = function () {
                _this._renderTargets.reset();
                if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
                    _this._renderTargets.push(_this._diffuseTexture);
                }
                if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
                    _this._renderTargets.push(_this._reflectionTexture);
                }
                return _this._renderTargets;
            };
            return _this;
        }
        Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
            /**
             * Experimental Internal Use Only.
             *
             * Key light Color in "perceptual value" meaning the color you would like to see on screen.
             * This acts as a helper to set the primary color to a more "human friendly" value.
             * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
             * output color as close as possible from the chosen value.
             * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
             * part of lighting setup.)
             */
            get: function () {
                return this.__perceptualColor;
            },
            set: function (value) {
                this.__perceptualColor = value;
                this._computePrimaryColorFromPerceptualColor();
                this._markAllSubMeshesAsLightsDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
            /**
             * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
             * The color opposite to the primary color is used at the level chosen to define what the black area would look.
             */
            get: function () {
                return this._primaryColorShadowLevel;
            },
            set: function (value) {
                this._primaryColorShadowLevel = value;
                this._computePrimaryColors();
                this._markAllSubMeshesAsLightsDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
            /**
             * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
             * The primary color is used at the level chosen to define what the white area would look.
             */
            get: function () {
                return this._primaryColorHighlightLevel;
            },
            set: function (value) {
                this._primaryColorHighlightLevel = value;
                this._computePrimaryColors();
                this._markAllSubMeshesAsLightsDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
            /**
             * Sets the reflection reflectance fresnel values according to the default standard
             * empirically know to work well :-)
             */
            set: function (value) {
                var reflectionWeight = value;
                if (reflectionWeight < 0.5) {
                    reflectionWeight = reflectionWeight * 2.0;
                    this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
                    this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
                }
                else {
                    reflectionWeight = reflectionWeight * 2.0 - 1.0;
                    this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
                    this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
            /**
             * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
             * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
             * Recommended to be keep at 1.0 except for special cases.
             */
            get: function () {
                return this._fovMultiplier;
            },
            set: function (value) {
                if (isNaN(value)) {
                    value = 1.0;
                }
                this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Attaches a new image processing configuration to the PBR Material.
         * @param configuration (if null the scene configuration will be use)
         */
        BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
            var _this = this;
            if (configuration === this._imageProcessingConfiguration) {
                return;
            }
            // Detaches observer.
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            // Pick the scene configuration if needed.
            if (!configuration) {
                this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
            }
            else {
                this._imageProcessingConfiguration = configuration;
            }
            // Attaches observer.
            if (this._imageProcessingConfiguration) {
                this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
                    _this._computePrimaryColorFromPerceptualColor();
                    _this._markAllSubMeshesAsImageProcessingDirty();
                });
            }
        };
        Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
            /**
             * Gets the image processing configuration used either in this material.
             */
            get: function () {
                return this._imageProcessingConfiguration;
            },
            /**
             * Sets the Default image processing configuration used either in the this material.
             *
             * If sets to null, the scene one is in use.
             */
            set: function (value) {
                this._attachImageProcessingConfiguration(value);
                // Ensure the effect will be rebuilt.
                this._markAllSubMeshesAsTexturesDirty();
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
            /**
             * Gets wether the color curves effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorCurvesEnabled;
            },
            /**
             * Sets wether the color curves effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorCurvesEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
            /**
             * Gets wether the color grading effect is enabled.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorGradingEnabled;
            },
            /**
             * Gets wether the color grading effect is enabled.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorGradingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
            /**
             * Gets wether tonemapping is enabled or not.
             */
            get: function () {
                return this._imageProcessingConfiguration.toneMappingEnabled;
            },
            /**
             * Sets wether tonemapping is enabled or not
             */
            set: function (value) {
                this._imageProcessingConfiguration.toneMappingEnabled = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            get: function () {
                return this._imageProcessingConfiguration.exposure;
            },
            /**
             * The camera exposure used on this material.
             * This property is here and not in the camera to allow controlling exposure without full screen post process.
             * This corresponds to a photographic exposure.
             */
            set: function (value) {
                this._imageProcessingConfiguration.exposure = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
            /**
             * Gets The camera contrast used on this material.
             */
            get: function () {
                return this._imageProcessingConfiguration.contrast;
            },
            /**
             * Sets The camera contrast used on this material.
             */
            set: function (value) {
                this._imageProcessingConfiguration.contrast = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
            /**
             * Gets the Color Grading 2D Lookup Texture.
             */
            get: function () {
                return this._imageProcessingConfiguration.colorGradingTexture;
            },
            /**
             * Sets the Color Grading 2D Lookup Texture.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorGradingTexture = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            get: function () {
                return this.imageProcessingConfiguration.colorCurves;
            },
            /**
             * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
             * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
             * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
             * corresponding to low luminance, medium luminance, and high luminance areas respectively.
             */
            set: function (value) {
                this.imageProcessingConfiguration.colorCurves = value;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
            /**
             * Gets a boolean indicating that current material needs to register RTT
             */
            get: function () {
                if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
                    return true;
                }
                if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
                    return true;
                }
                return false;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * The entire material has been created in order to prevent overdraw.
         * @returns false
         */
        BackgroundMaterial.prototype.needAlphaTesting = function () {
            return true;
        };
        /**
         * The entire material has been created in order to prevent overdraw.
         * @returns true if blending is enable
         */
        BackgroundMaterial.prototype.needAlphaBlending = function () {
            return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
        };
        /**
         * Checks wether the material is ready to be rendered for a given mesh.
         * @param mesh The mesh to render
         * @param subMesh The submesh to check against
         * @param useInstances Specify wether or not the material is used with instances
         * @returns true if all the dependencies are ready (Textures, Effects...)
         */
        BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
            var _this = this;
            if (useInstances === void 0) { useInstances = false; }
            if (subMesh.effect && this.isFrozen) {
                if (this._wasPreviouslyReady) {
                    return true;
                }
            }
            if (!subMesh._materialDefines) {
                subMesh._materialDefines = new BackgroundMaterialDefines();
            }
            var scene = this.getScene();
            var defines = subMesh._materialDefines;
            if (!this.checkReadyOnEveryCall && subMesh.effect) {
                if (defines._renderId === scene.getRenderId()) {
                    return true;
                }
            }
            var engine = scene.getEngine();
            // Lights
            BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
            defines._needNormals = true;
            // Textures
            if (defines._areTexturesDirty) {
                defines._needUVs = false;
                if (scene.texturesEnabled) {
                    if (scene.getEngine().getCaps().textureLOD) {
                        defines.TEXTURELODSUPPORT = true;
                    }
                    if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                        if (!this._diffuseTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
                        defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
                        defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
                        defines.OPACITYFRESNEL = this._opacityFresnel;
                    }
                    else {
                        defines.DIFFUSE = false;
                        defines.DIFFUSEHASALPHA = false;
                        defines.GAMMADIFFUSE = false;
                        defines.OPACITYFRESNEL = false;
                    }
                    var reflectionTexture = this._reflectionTexture;
                    if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        if (!reflectionTexture.isReadyOrNotBlocking()) {
                            return false;
                        }
                        defines.REFLECTION = true;
                        defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
                        defines.RGBDREFLECTION = reflectionTexture.isRGBD;
                        defines.REFLECTIONBLUR = this._reflectionBlur > 0;
                        defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
                        defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
                        defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
                        defines.REFLECTIONBGR = this.switchToBGR;
                        if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
                            defines.INVERTCUBICMAP = true;
                        }
                        defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
                        switch (reflectionTexture.coordinatesMode) {
                            case BABYLON.Texture.EXPLICIT_MODE:
                                defines.REFLECTIONMAP_EXPLICIT = true;
                                break;
                            case BABYLON.Texture.PLANAR_MODE:
                                defines.REFLECTIONMAP_PLANAR = true;
                                break;
                            case BABYLON.Texture.PROJECTION_MODE:
                                defines.REFLECTIONMAP_PROJECTION = true;
                                break;
                            case BABYLON.Texture.SKYBOX_MODE:
                                defines.REFLECTIONMAP_SKYBOX = true;
                                defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
                                break;
                            case BABYLON.Texture.SPHERICAL_MODE:
                                defines.REFLECTIONMAP_SPHERICAL = true;
                                break;
                            case BABYLON.Texture.EQUIRECTANGULAR_MODE:
                                defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
                                break;
                            case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
                                defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
                                break;
                            case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
                                defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
                                break;
                            case BABYLON.Texture.CUBIC_MODE:
                            case BABYLON.Texture.INVCUBIC_MODE:
                            default:
                                defines.REFLECTIONMAP_CUBIC = true;
                                break;
                        }
                        if (this.reflectionFresnel) {
                            defines.REFLECTIONFRESNEL = true;
                            defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
                            this._reflectionControls.x = this.reflectionAmount;
                            this._reflectionControls.y = this.reflectionReflectance0;
                            this._reflectionControls.z = this.reflectionReflectance90;
                            this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
                        }
                        else {
                            defines.REFLECTIONFRESNEL = false;
                            defines.REFLECTIONFALLOFF = false;
                        }
                    }
                    else {
                        defines.REFLECTION = false;
                        defines.REFLECTIONFRESNEL = false;
                        defines.REFLECTIONFALLOFF = false;
                        defines.REFLECTIONBLUR = false;
                        defines.REFLECTIONMAP_3D = false;
                        defines.REFLECTIONMAP_SPHERICAL = false;
                        defines.REFLECTIONMAP_PLANAR = false;
                        defines.REFLECTIONMAP_CUBIC = false;
                        defines.REFLECTIONMAP_PROJECTION = false;
                        defines.REFLECTIONMAP_SKYBOX = false;
                        defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
                        defines.REFLECTIONMAP_EXPLICIT = false;
                        defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
                        defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
                        defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
                        defines.INVERTCUBICMAP = false;
                        defines.REFLECTIONMAP_OPPOSITEZ = false;
                        defines.LODINREFLECTIONALPHA = false;
                        defines.GAMMAREFLECTION = false;
                        defines.RGBDREFLECTION = false;
                    }
                }
                defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
                defines.USERGBCOLOR = this._useRGBColor;
                defines.NOISE = this._enableNoise;
            }
            if (defines._areLightsDirty) {
                defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
            }
            if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
                if (!this._imageProcessingConfiguration.isReady()) {
                    return false;
                }
                this._imageProcessingConfiguration.prepareDefines(defines);
            }
            // Misc.
            BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
            // Values that need to be evaluated on every frame
            BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
            // Attribs
            if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
                if (mesh) {
                    if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
                        mesh.createNormals(true);
                        BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
                    }
                }
            }
            // Get correct effect
            if (defines.isDirty) {
                defines.markAsProcessed();
                scene.resetCachedMaterial();
                // Fallbacks
                var fallbacks = new BABYLON.EffectFallbacks();
                if (defines.FOG) {
                    fallbacks.addFallback(0, "FOG");
                }
                if (defines.POINTSIZE) {
                    fallbacks.addFallback(1, "POINTSIZE");
                }
                BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
                if (defines.NUM_BONE_INFLUENCERS > 0) {
                    fallbacks.addCPUSkinningFallback(0, mesh);
                }
                //Attributes
                var attribs = [BABYLON.VertexBuffer.PositionKind];
                if (defines.NORMAL) {
                    attribs.push(BABYLON.VertexBuffer.NormalKind);
                }
                if (defines.UV1) {
                    attribs.push(BABYLON.VertexBuffer.UVKind);
                }
                if (defines.UV2) {
                    attribs.push(BABYLON.VertexBuffer.UV2Kind);
                }
                BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
                BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
                var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
                    "vFogInfos", "vFogColor", "pointSize",
                    "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
                    "vPrimaryColor", "vPrimaryColorShadow",
                    "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
                    "shadowLevel", "alpha",
                    "vBackgroundCenter", "vReflectionControl",
                    "vDiffuseInfos", "diffuseMatrix",
                ];
                var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
                var uniformBuffers = ["Material", "Scene"];
                if (BABYLON.ImageProcessingConfiguration) {
                    BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
                    BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
                }
                BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
                    uniformsNames: uniforms,
                    uniformBuffersNames: uniformBuffers,
                    samplers: samplers,
                    defines: defines,
                    maxSimultaneousLights: this._maxSimultaneousLights
                });
                var onCompiled = function (effect) {
                    if (_this.onCompiled) {
                        _this.onCompiled(effect);
                    }
                    _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
                };
                var join = defines.toString();
                subMesh.setEffect(scene.getEngine().createEffect("background", {
                    attributes: attribs,
                    uniformsNames: uniforms,
                    uniformBuffersNames: uniformBuffers,
                    samplers: samplers,
                    defines: join,
                    fallbacks: fallbacks,
                    onCompiled: onCompiled,
                    onError: this.onError,
                    indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
                }, engine), defines);
                this.buildUniformLayout();
            }
            if (!subMesh.effect || !subMesh.effect.isReady()) {
                return false;
            }
            defines._renderId = scene.getRenderId();
            this._wasPreviouslyReady = true;
            return true;
        };
        /**
         * Compute the primary color according to the chosen perceptual color.
         */
        BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
            if (!this.__perceptualColor) {
                return;
            }
            this._primaryColor.copyFrom(this.__perceptualColor);
            // Revert gamma space.
            this._primaryColor.toLinearSpaceToRef(this._primaryColor);
            // Revert image processing configuration.
            if (this._imageProcessingConfiguration) {
                // Revert Exposure.
                this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
            }
            this._computePrimaryColors();
        };
        /**
         * Compute the highlights and shadow colors according to their chosen levels.
         */
        BackgroundMaterial.prototype._computePrimaryColors = function () {
            if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
                return;
            }
            // Find the highlight color based on the configuration.
            this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
            this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
            // Find the shadow color based on the configuration.
            this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
            this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
            this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
        };
        /**
         * Build the uniform buffer used in the material.
         */
        BackgroundMaterial.prototype.buildUniformLayout = function () {
            // Order is important !
            this._uniformBuffer.addUniform("vPrimaryColor", 4);
            this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
            this._uniformBuffer.addUniform("vDiffuseInfos", 2);
            this._uniformBuffer.addUniform("vReflectionInfos", 2);
            this._uniformBuffer.addUniform("diffuseMatrix", 16);
            this._uniformBuffer.addUniform("reflectionMatrix", 16);
            this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
            this._uniformBuffer.addUniform("fFovMultiplier", 1);
            this._uniformBuffer.addUniform("pointSize", 1);
            this._uniformBuffer.addUniform("shadowLevel", 1);
            this._uniformBuffer.addUniform("alpha", 1);
            this._uniformBuffer.addUniform("vBackgroundCenter", 3);
            this._uniformBuffer.addUniform("vReflectionControl", 4);
            this._uniformBuffer.create();
        };
        /**
         * Unbind the material.
         */
        BackgroundMaterial.prototype.unbind = function () {
            if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
                this._uniformBuffer.setTexture("diffuseSampler", null);
            }
            if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
                this._uniformBuffer.setTexture("reflectionSampler", null);
            }
            _super.prototype.unbind.call(this);
        };
        /**
         * Bind only the world matrix to the material.
         * @param world The world matrix to bind.
         */
        BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
            this._activeEffect.setMatrix("world", world);
        };
        /**
         * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
         * @param world The world matrix to bind.
         * @param subMesh The submesh to bind for.
         */
        BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
            var scene = this.getScene();
            var defines = subMesh._materialDefines;
            if (!defines) {
                return;
            }
            var effect = subMesh.effect;
            if (!effect) {
                return;
            }
            this._activeEffect = effect;
            // Matrices
            this.bindOnlyWorldMatrix(world);
            // Bones
            BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
            var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
            if (mustRebind) {
                this._uniformBuffer.bindToEffect(effect, "Material");
                this.bindViewProjection(effect);
                var reflectionTexture = this._reflectionTexture;
                if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
                    // Texture uniforms
                    if (scene.texturesEnabled) {
                        if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                            this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
                            BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
                        }
                        if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                            this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
                            this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
                            this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
                        }
                    }
                    if (this.shadowLevel > 0) {
                        this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
                    }
                    this._uniformBuffer.updateFloat("alpha", this.alpha);
                    // Point size
                    if (this.pointsCloud) {
                        this._uniformBuffer.updateFloat("pointSize", this.pointSize);
                    }
                    if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
                        this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
                        this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
                    }
                    else {
                        this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
                    }
                }
                this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
                // Textures
                if (scene.texturesEnabled) {
                    if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
                        this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
                    }
                    if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
                        if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
                            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
                        }
                        else if (!defines.REFLECTIONBLUR) {
                            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
                        }
                        else {
                            this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
                            this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
                            this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
                        }
                        if (defines.REFLECTIONFRESNEL) {
                            this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
                            this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
                        }
                    }
                }
                // Clip plane
                BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
                BABYLON.MaterialHelper.BindEyePosition(effect, scene);
            }
            if (mustRebind || !this.isFrozen) {
                if (scene.lightsEnabled) {
                    BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
                }
                // View
                this.bindView(effect);
                // Fog
                BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
                // image processing
                if (this._imageProcessingConfiguration) {
                    this._imageProcessingConfiguration.bind(this._activeEffect);
                }
            }
            this._uniformBuffer.update();
            this._afterBind(mesh, this._activeEffect);
        };
        /**
         * Dispose the material.
         * @param forceDisposeEffect Force disposal of the associated effect.
         * @param forceDisposeTextures Force disposal of the associated textures.
         */
        BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
            if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
            if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
            if (forceDisposeTextures) {
                if (this.diffuseTexture) {
                    this.diffuseTexture.dispose();
                }
                if (this.reflectionTexture) {
                    this.reflectionTexture.dispose();
                }
            }
            this._renderTargets.dispose();
            if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
                this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
            }
            _super.prototype.dispose.call(this, forceDisposeEffect);
        };
        /**
         * Clones the material.
         * @param name The cloned name.
         * @returns The cloned material.
         */
        BackgroundMaterial.prototype.clone = function (name) {
            var _this = this;
            return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
        };
        /**
         * Serializes the current material to its JSON representation.
         * @returns The JSON representation.
         */
        BackgroundMaterial.prototype.serialize = function () {
            var serializationObject = BABYLON.SerializationHelper.Serialize(this);
            serializationObject.customType = "BABYLON.BackgroundMaterial";
            return serializationObject;
        };
        /**
         * Gets the class name of the material
         * @returns "BackgroundMaterial"
         */
        BackgroundMaterial.prototype.getClassName = function () {
            return "BackgroundMaterial";
        };
        /**
         * Parse a JSON input to create back a background material.
         * @param source The JSON data to parse
         * @param scene The scene to create the parsed material in
         * @param rootUrl The root url of the assets the material depends upon
         * @returns the instantiated BackgroundMaterial.
         */
        BackgroundMaterial.Parse = function (source, scene, rootUrl) {
            return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
        };
        /**
         * Standard reflectance value at parallel view angle.
         */
        BackgroundMaterial.StandardReflectance0 = 0.05;
        /**
         * Standard reflectance value at grazing angle.
         */
        BackgroundMaterial.StandardReflectance90 = 0.5;
        __decorate([
            BABYLON.serializeAsColor3()
        ], BackgroundMaterial.prototype, "_primaryColor", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], BackgroundMaterial.prototype, "primaryColor", void 0);
        __decorate([
            BABYLON.serializeAsColor3()
        ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
        ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
        __decorate([
            BABYLON.serializeAsTexture()
        ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
        __decorate([
            BABYLON.serializeAsTexture()
        ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "shadowLights", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "shadowLevel", void 0);
        __decorate([
            BABYLON.serializeAsVector3()
        ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "sceneCenter", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "useRGBColor", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_enableNoise", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "enableNoise", void 0);
        __decorate([
            BABYLON.serialize()
        ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
        ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
        __decorate([
            BABYLON.serializeAsImageProcessingConfiguration()
        ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
        return BackgroundMaterial;
    }(BABYLON.PushMaterial));
    BABYLON.BackgroundMaterial = BackgroundMaterial;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.backgroundMaterial.js.map

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var BABYLON;
(function (BABYLON) {
    /**
     * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
     * It includes by default a skybox and a ground relying on the BackgroundMaterial.
     * It also helps with the default setup of your imageProcessing configuration.
     */
    var EnvironmentHelper = /** @class */ (function () {
        /**
         * constructor
         * @param options
         * @param scene The scene to add the material to
         */
        function EnvironmentHelper(options, scene) {
            var _this = this;
            this._errorHandler = function (message, exception) {
                _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
            };
            this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
            this._scene = scene;
            this.onErrorObservable = new BABYLON.Observable();
            this._setupBackground();
            this._setupImageProcessing();
        }
        /**
         * Creates the default options for the helper.
         */
        EnvironmentHelper._getDefaultOptions = function () {
            return {
                createGround: true,
                groundSize: 15,
                groundTexture: this._groundTextureCDNUrl,
                groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
                groundOpacity: 0.9,
                enableGroundShadow: true,
                groundShadowLevel: 0.5,
                enableGroundMirror: false,
                groundMirrorSizeRatio: 0.3,
                groundMirrorBlurKernel: 64,
                groundMirrorAmount: 1,
                groundMirrorFresnelWeight: 1,
                groundMirrorFallOffDistance: 0,
                groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
                groundYBias: 0.00001,
                createSkybox: true,
                skyboxSize: 20,
                skyboxTexture: this._skyboxTextureCDNUrl,
                skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
                backgroundYRotation: 0,
                sizeAuto: true,
                rootPosition: BABYLON.Vector3.Zero(),
                setupImageProcessing: true,
                environmentTexture: this._environmentTextureCDNUrl,
                cameraExposure: 0.8,
                cameraContrast: 1.2,
                toneMappingEnabled: true,
            };
        };
        Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
            /**
             * Gets the root mesh created by the helper.
             */
            get: function () {
                return this._rootMesh;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
            /**
             * Gets the skybox created by the helper.
             */
            get: function () {
                return this._skybox;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
            /**
             * Gets the skybox texture created by the helper.
             */
            get: function () {
                return this._skyboxTexture;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
            /**
             * Gets the skybox material created by the helper.
             */
            get: function () {
                return this._skyboxMaterial;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "ground", {
            /**
             * Gets the ground mesh created by the helper.
             */
            get: function () {
                return this._ground;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
            /**
             * Gets the ground texture created by the helper.
             */
            get: function () {
                return this._groundTexture;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
            /**
             * Gets the ground mirror created by the helper.
             */
            get: function () {
                return this._groundMirror;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
            /**
             * Gets the ground mirror render list to helps pushing the meshes
             * you wish in the ground reflection.
             */
            get: function () {
                if (this._groundMirror) {
                    return this._groundMirror.renderList;
                }
                return null;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
            /**
             * Gets the ground material created by the helper.
             */
            get: function () {
                return this._groundMaterial;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Updates the background according to the new options
         * @param options
         */
        EnvironmentHelper.prototype.updateOptions = function (options) {
            var newOptions = __assign({}, this._options, options);
            if (this._ground && !newOptions.createGround) {
                this._ground.dispose();
                this._ground = null;
            }
            if (this._groundMaterial && !newOptions.createGround) {
                this._groundMaterial.dispose();
                this._groundMaterial = null;
            }
            if (this._groundTexture) {
                if (this._options.groundTexture != newOptions.groundTexture) {
                    this._groundTexture.dispose();
                    this._groundTexture = null;
                }
            }
            if (this._skybox && !newOptions.createSkybox) {
                this._skybox.dispose();
                this._skybox = null;
            }
            if (this._skyboxMaterial && !newOptions.createSkybox) {
                this._skyboxMaterial.dispose();
                this._skyboxMaterial = null;
            }
            if (this._skyboxTexture) {
                if (this._options.skyboxTexture != newOptions.skyboxTexture) {
                    this._skyboxTexture.dispose();
                    this._skyboxTexture = null;
                }
            }
            if (this._groundMirror && !newOptions.enableGroundMirror) {
                this._groundMirror.dispose();
                this._groundMirror = null;
            }
            if (this._scene.environmentTexture) {
                if (this._options.environmentTexture != newOptions.environmentTexture) {
                    this._scene.environmentTexture.dispose();
                }
            }
            this._options = newOptions;
            this._setupBackground();
            this._setupImageProcessing();
        };
        /**
         * Sets the primary color of all the available elements.
         * @param color the main color to affect to the ground and the background
         */
        EnvironmentHelper.prototype.setMainColor = function (color) {
            if (this.groundMaterial) {
                this.groundMaterial.primaryColor = color;
            }
            if (this.skyboxMaterial) {
                this.skyboxMaterial.primaryColor = color;
            }
            if (this.groundMirror) {
                this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
            }
        };
        /**
         * Setup the image processing according to the specified options.
         */
        EnvironmentHelper.prototype._setupImageProcessing = function () {
            if (this._options.setupImageProcessing) {
                this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
                this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
                this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
                this._setupEnvironmentTexture();
            }
        };
        /**
         * Setup the environment texture according to the specified options.
         */
        EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
            if (this._scene.environmentTexture) {
                return;
            }
            if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
                this._scene.environmentTexture = this._options.environmentTexture;
                return;
            }
            var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
            this._scene.environmentTexture = environmentTexture;
        };
        /**
         * Setup the background according to the specified options.
         */
        EnvironmentHelper.prototype._setupBackground = function () {
            if (!this._rootMesh) {
                this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
            }
            this._rootMesh.rotation.y = this._options.backgroundYRotation;
            var sceneSize = this._getSceneSize();
            if (this._options.createGround) {
                this._setupGround(sceneSize);
                this._setupGroundMaterial();
                this._setupGroundDiffuseTexture();
                if (this._options.enableGroundMirror) {
                    this._setupGroundMirrorTexture(sceneSize);
                }
                this._setupMirrorInGroundMaterial();
            }
            if (this._options.createSkybox) {
                this._setupSkybox(sceneSize);
                this._setupSkyboxMaterial();
                this._setupSkyboxReflectionTexture();
            }
            this._rootMesh.position.x = sceneSize.rootPosition.x;
            this._rootMesh.position.z = sceneSize.rootPosition.z;
            this._rootMesh.position.y = sceneSize.rootPosition.y;
        };
        /**
         * Get the scene sizes according to the setup.
         */
        EnvironmentHelper.prototype._getSceneSize = function () {
            var _this = this;
            var groundSize = this._options.groundSize;
            var skyboxSize = this._options.skyboxSize;
            var rootPosition = this._options.rootPosition;
            if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
                return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
            }
            var sceneExtends = this._scene.getWorldExtends(function (mesh) {
                return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
            });
            var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
            if (this._options.sizeAuto) {
                if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
                    this._scene.activeCamera.upperRadiusLimit) {
                    groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
                    skyboxSize = groundSize;
                }
                var sceneDiagonalLenght = sceneDiagonal.length();
                if (sceneDiagonalLenght > groundSize) {
                    groundSize = sceneDiagonalLenght * 2;
                    skyboxSize = groundSize;
                }
                // 10 % bigger.
                groundSize *= 1.1;
                skyboxSize *= 1.5;
                rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
                rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
            }
            return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
        };
        /**
         * Setup the ground according to the specified options.
         */
        EnvironmentHelper.prototype._setupGround = function (sceneSize) {
            var _this = this;
            if (!this._ground || this._ground.isDisposed()) {
                this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
                this._ground.rotation.x = Math.PI / 2; // Face up by default.
                this._ground.parent = this._rootMesh;
                this._ground.onDisposeObservable.add(function () { _this._ground = null; });
            }
            this._ground.receiveShadows = this._options.enableGroundShadow;
        };
        /**
         * Setup the ground material according to the specified options.
         */
        EnvironmentHelper.prototype._setupGroundMaterial = function () {
            if (!this._groundMaterial) {
                this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
            }
            this._groundMaterial.alpha = this._options.groundOpacity;
            this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
            this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
            this._groundMaterial.primaryColor = this._options.groundColor;
            this._groundMaterial.useRGBColor = false;
            this._groundMaterial.enableNoise = true;
            if (this._ground) {
                this._ground.material = this._groundMaterial;
            }
        };
        /**
         * Setup the ground diffuse texture according to the specified options.
         */
        EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
            if (!this._groundMaterial) {
                return;
            }
            if (this._groundTexture) {
                return;
            }
            if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
                this._groundMaterial.diffuseTexture = this._options.groundTexture;
                return;
            }
            var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
            diffuseTexture.gammaSpace = false;
            diffuseTexture.hasAlpha = true;
            this._groundMaterial.diffuseTexture = diffuseTexture;
        };
        /**
         * Setup the ground mirror texture according to the specified options.
         */
        EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
            var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
            if (!this._groundMirror) {
                this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
                this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
                this._groundMirror.anisotropicFilteringLevel = 1;
                this._groundMirror.wrapU = wrapping;
                this._groundMirror.wrapV = wrapping;
                this._groundMirror.gammaSpace = false;
                if (this._groundMirror.renderList) {
                    for (var i = 0; i < this._scene.meshes.length; i++) {
                        var mesh = this._scene.meshes[i];
                        if (mesh !== this._ground &&
                            mesh !== this._skybox &&
                            mesh !== this._rootMesh) {
                            this._groundMirror.renderList.push(mesh);
                        }
                    }
                }
            }
            this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
            this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
        };
        /**
         * Setup the ground to receive the mirror texture.
         */
        EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
            if (this._groundMaterial) {
                this._groundMaterial.reflectionTexture = this._groundMirror;
                this._groundMaterial.reflectionFresnel = true;
                this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
                this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
                this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
            }
        };
        /**
         * Setup the skybox according to the specified options.
         */
        EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
            var _this = this;
            if (!this._skybox || this._skybox.isDisposed()) {
                this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
                this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
            }
            this._skybox.parent = this._rootMesh;
        };
        /**
         * Setup the skybox material according to the specified options.
         */
        EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
            if (!this._skybox) {
                return;
            }
            if (!this._skyboxMaterial) {
                this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
            }
            this._skyboxMaterial.useRGBColor = false;
            this._skyboxMaterial.primaryColor = this._options.skyboxColor;
            this._skyboxMaterial.enableNoise = true;
            this._skybox.material = this._skyboxMaterial;
        };
        /**
         * Setup the skybox reflection texture according to the specified options.
         */
        EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
            if (!this._skyboxMaterial) {
                return;
            }
            if (this._skyboxTexture) {
                return;
            }
            if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
                this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
                return;
            }
            this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
            this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
            this._skyboxTexture.gammaSpace = false;
            this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
        };
        /**
         * Dispose all the elements created by the Helper.
         */
        EnvironmentHelper.prototype.dispose = function () {
            if (this._groundMaterial) {
                this._groundMaterial.dispose(true, true);
            }
            if (this._skyboxMaterial) {
                this._skyboxMaterial.dispose(true, true);
            }
            this._rootMesh.dispose(false);
        };
        /**
         * Default ground texture URL.
         */
        EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
        /**
         * Default skybox texture URL.
         */
        EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
        /**
         * Default environment texture URL.
         */
        EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
        return EnvironmentHelper;
    }());
    BABYLON.EnvironmentHelper = EnvironmentHelper;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.environmentHelper.js.map

var BABYLON;
(function (BABYLON) {
    /** Internal class used to store shapes for emitters */
    var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
        function ParticleSystemSetEmitterCreationOptions() {
        }
        return ParticleSystemSetEmitterCreationOptions;
    }());
    /**
     * Represents a set of particle systems working together to create a specific effect
     */
    var ParticleSystemSet = /** @class */ (function () {
        function ParticleSystemSet() {
            /**
             * Gets the particle system list
             */
            this.systems = new Array();
        }
        Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
            /**
             * Gets the emitter node used with this set
             */
            get: function () {
                return this._emitterNode;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Creates a new emitter mesh as a sphere
         * @param options defines the options used to create the sphere
         * @param renderingGroupId defines the renderingGroupId to use for the sphere
         * @param scene defines the hosting scene
         */
        ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
            if (this._emitterNode) {
                this._emitterNode.dispose();
            }
            this._emitterCreationOptions = {
                kind: "Sphere",
                options: options,
                renderingGroupId: renderingGroupId
            };
            var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
            emitterMesh.renderingGroupId = renderingGroupId;
            var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
            material.emissiveColor = options.color;
            emitterMesh.material = material;
            for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
                var system = _a[_i];
                system.emitter = emitterMesh;
            }
            this._emitterNode = emitterMesh;
        };
        /**
         * Starts all particle systems of the set
         * @param emitter defines an optional mesh to use as emitter for the particle systems
         */
        ParticleSystemSet.prototype.start = function (emitter) {
            for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
                var system = _a[_i];
                if (emitter) {
                    system.emitter = emitter;
                }
                system.start();
            }
        };
        /**
         * Release all associated resources
         */
        ParticleSystemSet.prototype.dispose = function () {
            for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
                var system = _a[_i];
                system.dispose();
            }
            this.systems = [];
            if (this._emitterNode) {
                this._emitterNode.dispose();
                this._emitterNode = null;
            }
        };
        /**
         * Serialize the set into a JSON compatible object
         * @returns a JSON compatible representation of the set
         */
        ParticleSystemSet.prototype.serialize = function () {
            var result = {};
            result.systems = [];
            for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
                var system = _a[_i];
                result.systems.push(system.serialize());
            }
            if (this._emitterNode) {
                result.emitter = this._emitterCreationOptions;
            }
            return result;
        };
        /**
         * Parse a new ParticleSystemSet from a serialized source
         * @param data defines a JSON compatible representation of the set
         * @param scene defines the hosting scene
         * @param gpu defines if we want GPU particles or CPU particles
         * @returns a new ParticleSystemSet
         */
        ParticleSystemSet.Parse = function (data, scene, gpu) {
            if (gpu === void 0) { gpu = false; }
            var result = new ParticleSystemSet();
            var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
            scene = scene || BABYLON.Engine.LastCreatedScene;
            for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
                var system = _a[_i];
                result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
            }
            if (data.emitter) {
                var options = data.emitter.options;
                switch (data.emitter.kind) {
                    case "Sphere":
                        result.setEmitterAsSphere({
                            diameter: options.diameter,
                            segments: options.segments,
                            color: BABYLON.Color3.FromArray(options.color)
                        }, data.emitter.renderingGroupId, scene);
                        break;
                }
            }
            return result;
        };
        return ParticleSystemSet;
    }());
    BABYLON.ParticleSystemSet = ParticleSystemSet;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.particleSystemSet.js.map

var BABYLON;
(function (BABYLON) {
    /**
     * This class is made for on one-liner static method to help creating particle system set.
     */
    var ParticleHelper = /** @class */ (function () {
        function ParticleHelper() {
        }
        /**
         * Create a default particle system that you can tweak
         * @param emitter defines the emitter to use
         * @param capacity defines the system capacity (default is 500 particles)
         * @param scene defines the hosting scene
         * @param useGPU defines if a GPUParticleSystem must be created (default is false)
         * @returns the new Particle system
         */
        ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
            if (capacity === void 0) { capacity = 500; }
            if (useGPU === void 0) { useGPU = false; }
            var system;
            if (useGPU) {
                system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
            }
            else {
                system = new BABYLON.ParticleSystem("default system", capacity, scene);
            }
            system.emitter = emitter;
            system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
            system.createConeEmitter(0.1, Math.PI / 4);
            // Particle color
            system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
            system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
            // Particle Size
            system.minSize = 0.1;
            system.maxSize = 0.1;
            // Emission speed
            system.minEmitPower = 2;
            system.maxEmitPower = 2;
            // Update speed
            system.updateSpeed = 1 / 60;
            system.emitRate = 30;
            return system;
        };
        /**
         * This is the main static method (one-liner) of this helper to create different particle systems
         * @param type This string represents the type to the particle system to create
         * @param scene The scene where the particle system should live
         * @param gpu If the system will use gpu
         * @returns the ParticleSystemSet created
         */
        ParticleHelper.CreateAsync = function (type, scene, gpu) {
            if (gpu === void 0) { gpu = false; }
            if (!scene) {
                scene = BABYLON.Engine.LastCreatedScene;
            }
            var token = {};
            scene._addPendingData(token);
            return new Promise(function (resolve, reject) {
                if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
                    scene._removePendingData(token);
                    return reject("Particle system with GPU is not supported.");
                }
                BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
                    scene._removePendingData(token);
                    var newData = JSON.parse(data.toString());
                    return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
                }, undefined, undefined, undefined, function (req, exception) {
                    scene._removePendingData(token);
                    return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
                });
            });
        };
        /**
         * Static function used to export a particle system to a ParticleSystemSet variable.
         * Please note that the emitter shape is not exported
         * @param systems defines the particle systems to export
         * @returns the created particle system set
         */
        ParticleHelper.ExportSet = function (systems) {
            var set = new BABYLON.ParticleSystemSet();
            for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
                var system = systems_1[_i];
                set.systems.push(system);
            }
            return set;
        };
        /**
         * Gets or sets base Assets URL
         */
        ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
        return ParticleHelper;
    }());
    BABYLON.ParticleHelper = ParticleHelper;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.particleHelper.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
     * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
     * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
     * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
     */
    var VideoDome = /** @class */ (function (_super) {
        __extends(VideoDome, _super);
        /**
         * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
         * @param name Element's name, child elements will append suffixes for their own names.
         * @param urlsOrVideo defines the url(s) or the video element to use
         * @param options An object containing optional or exposed sub element properties
         */
        function VideoDome(name, urlsOrVideo, options, scene) {
            var _this = _super.call(this, name, scene) || this;
            _this._useDirectMapping = false;
            // set defaults and manage values
            name = name || "videoDome";
            options.resolution = (Math.abs(options.resolution) | 0) || 32;
            options.clickToPlay = Boolean(options.clickToPlay);
            options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
            options.loop = options.loop === undefined ? true : Boolean(options.loop);
            options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
            if (options.useDirectMapping === undefined) {
                _this._useDirectMapping = true;
            }
            else {
                _this._useDirectMapping = options.useDirectMapping;
            }
            _this._setReady(false);
            // create
            var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
            var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
            var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
            _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
            texture.onLoadObservable.addOnce(function () {
                _this._setReady(true);
            });
            // configure material
            material.useEquirectangularFOV = true;
            material.fovMultiplier = 1.0;
            material.opacityFresnel = false;
            if (_this._useDirectMapping) {
                texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                material.diffuseTexture = texture;
            }
            else {
                texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
                texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                material.reflectionTexture = texture;
            }
            // configure mesh
            _this._mesh.material = material;
            _this._mesh.parent = _this;
            // optional configuration
            if (options.clickToPlay) {
                scene.onPointerUp = function () {
                    _this._videoTexture.video.play();
                };
            }
            return _this;
        }
        Object.defineProperty(VideoDome.prototype, "videoTexture", {
            /**
             * Gets the video texture being displayed on the sphere
             */
            get: function () {
                return this._videoTexture;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
            /**
             * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
             * Also see the options.resolution property.
             */
            get: function () {
                return this._material.fovMultiplier;
            },
            set: function (value) {
                this._material.fovMultiplier = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Releases resources associated with this node.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            this._videoTexture.dispose();
            this._mesh.dispose();
            this._material.dispose();
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        return VideoDome;
    }(BABYLON.TransformNode));
    BABYLON.VideoDome = VideoDome;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.videoDome.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
     * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
     * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
     * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
     */
    var PhotoDome = /** @class */ (function (_super) {
        __extends(PhotoDome, _super);
        /**
         * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
         * @param name Element's name, child elements will append suffixes for their own names.
         * @param urlsOfPhoto defines the url of the photo to display
         * @param options defines an object containing optional or exposed sub element properties
         * @param onError defines a callback called when an error occured while loading the texture
         */
        function PhotoDome(name, urlOfPhoto, options, scene, onError) {
            if (onError === void 0) { onError = null; }
            var _this = _super.call(this, name, scene) || this;
            _this._useDirectMapping = false;
            /**
             * Observable raised when an error occured while loading the 360 image
             */
            _this.onLoadErrorObservable = new BABYLON.Observable();
            // set defaults and manage values
            name = name || "photoDome";
            options.resolution = (Math.abs(options.resolution) | 0) || 32;
            options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
            if (options.useDirectMapping === undefined) {
                _this._useDirectMapping = true;
            }
            else {
                _this._useDirectMapping = options.useDirectMapping;
            }
            _this._setReady(false);
            // create
            var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
            _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
            // configure material
            material.opacityFresnel = false;
            material.useEquirectangularFOV = true;
            material.fovMultiplier = 1.0;
            _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
                _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
                if (onError) {
                    onError(message, exception);
                }
            });
            _this.photoTexture.onLoadObservable.addOnce(function () {
                _this._setReady(true);
            });
            // configure mesh
            _this._mesh.material = material;
            _this._mesh.parent = _this;
            return _this;
        }
        Object.defineProperty(PhotoDome.prototype, "photoTexture", {
            /**
             * Gets or sets the texture being displayed on the sphere
             */
            get: function () {
                return this._photoTexture;
            },
            set: function (value) {
                if (this._photoTexture === value) {
                    return;
                }
                this._photoTexture = value;
                if (this._useDirectMapping) {
                    this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    this._material.diffuseTexture = this._photoTexture;
                }
                else {
                    this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
                    this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
                    this._material.reflectionTexture = this._photoTexture;
                }
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
            /**
             * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
             * Also see the options.resolution property.
             */
            get: function () {
                return this._material.fovMultiplier;
            },
            set: function (value) {
                this._material.fovMultiplier = value;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Releases resources associated with this node.
         * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
         * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
         */
        PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
            if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
            this._photoTexture.dispose();
            this._mesh.dispose();
            this._material.dispose();
            this.onLoadErrorObservable.clear();
            _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
        };
        return PhotoDome;
    }(BABYLON.TransformNode));
    BABYLON.PhotoDome = PhotoDome;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.photoDome.js.map

var BABYLON;
(function (BABYLON) {
    /** @hidden */
    var _OcclusionDataStorage = /** @class */ (function () {
        function _OcclusionDataStorage() {
            /** @hidden */
            this.occlusionInternalRetryCounter = 0;
            /** @hidden */
            this.isOcclusionQueryInProgress = false;
            /** @hidden */
            this.isOccluded = false;
            /** @hidden */
            this.occlusionRetryCount = -1;
            /** @hidden */
            this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
            /** @hidden */
            this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
        }
        return _OcclusionDataStorage;
    }());
    BABYLON.Engine.prototype.createQuery = function () {
        return this._gl.createQuery();
    };
    BABYLON.Engine.prototype.deleteQuery = function (query) {
        this._gl.deleteQuery(query);
        return this;
    };
    BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
        return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
    };
    BABYLON.Engine.prototype.getQueryResult = function (query) {
        return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
    };
    BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
        var glAlgorithm = this._getGlAlgorithmType(algorithmType);
        this._gl.beginQuery(glAlgorithm, query);
        return this;
    };
    BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
        var glAlgorithm = this._getGlAlgorithmType(algorithmType);
        this._gl.endQuery(glAlgorithm);
        return this;
    };
    BABYLON.Engine.prototype._createTimeQuery = function () {
        var timerQuery = this.getCaps().timerQuery;
        if (timerQuery.createQueryEXT) {
            return timerQuery.createQueryEXT();
        }
        return this.createQuery();
    };
    BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
        var timerQuery = this.getCaps().timerQuery;
        if (timerQuery.deleteQueryEXT) {
            timerQuery.deleteQueryEXT(query);
            return;
        }
        this.deleteQuery(query);
    };
    BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
        var timerQuery = this.getCaps().timerQuery;
        if (timerQuery.getQueryObjectEXT) {
            return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
        }
        return this.getQueryResult(query);
    };
    BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
        var timerQuery = this.getCaps().timerQuery;
        if (timerQuery.getQueryObjectEXT) {
            return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
        }
        return this.isQueryResultAvailable(query);
    };
    BABYLON.Engine.prototype.startTimeQuery = function () {
        var caps = this.getCaps();
        var timerQuery = caps.timerQuery;
        if (!timerQuery) {
            return null;
        }
        var token = new BABYLON._TimeToken();
        this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
        if (caps.canUseTimestampForTimerQuery) {
            token._startTimeQuery = this._createTimeQuery();
            timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
        }
        else {
            if (this._currentNonTimestampToken) {
                return this._currentNonTimestampToken;
            }
            token._timeElapsedQuery = this._createTimeQuery();
            if (timerQuery.beginQueryEXT) {
                timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
            }
            else {
                this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
            }
            this._currentNonTimestampToken = token;
        }
        return token;
    };
    BABYLON.Engine.prototype.endTimeQuery = function (token) {
        var caps = this.getCaps();
        var timerQuery = caps.timerQuery;
        if (!timerQuery || !token) {
            return -1;
        }
        if (caps.canUseTimestampForTimerQuery) {
            if (!token._startTimeQuery) {
                return -1;
            }
            if (!token._endTimeQuery) {
                token._endTimeQuery = this._createTimeQuery();
                timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
            }
        }
        else if (!token._timeElapsedQueryEnded) {
            if (!token._timeElapsedQuery) {
                return -1;
            }
            if (timerQuery.endQueryEXT) {
                timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
            }
            else {
                this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
            }
            token._timeElapsedQueryEnded = true;
        }
        var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
        var available = false;
        if (token._endTimeQuery) {
            available = this._getTimeQueryAvailability(token._endTimeQuery);
        }
        else if (token._timeElapsedQuery) {
            available = this._getTimeQueryAvailability(token._timeElapsedQuery);
        }
        if (available && !disjoint) {
            var result = 0;
            if (caps.canUseTimestampForTimerQuery) {
                if (!token._startTimeQuery || !token._endTimeQuery) {
                    return -1;
                }
                var timeStart = this._getTimeQueryResult(token._startTimeQuery);
                var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
                result = timeEnd - timeStart;
                this._deleteTimeQuery(token._startTimeQuery);
                this._deleteTimeQuery(token._endTimeQuery);
                token._startTimeQuery = null;
                token._endTimeQuery = null;
            }
            else {
                if (!token._timeElapsedQuery) {
                    return -1;
                }
                result = this._getTimeQueryResult(token._timeElapsedQuery);
                this._deleteTimeQuery(token._timeElapsedQuery);
                token._timeElapsedQuery = null;
                token._timeElapsedQueryEnded = false;
                this._currentNonTimestampToken = null;
            }
            return result;
        }
        return -1;
    };
    BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
        return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
    };
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
        get: function () {
            return this._occlusionDataStorage.isOcclusionQueryInProgress;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
        get: function () {
            if (!this.__occlusionDataStorage) {
                this.__occlusionDataStorage = new _OcclusionDataStorage();
            }
            return this.__occlusionDataStorage;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
        get: function () {
            return this._occlusionDataStorage.isOccluded;
        },
        set: function (value) {
            this._occlusionDataStorage.isOccluded = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
        get: function () {
            return this._occlusionDataStorage.occlusionQueryAlgorithmType;
        },
        set: function (value) {
            this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
        get: function () {
            return this._occlusionDataStorage.occlusionType;
        },
        set: function (value) {
            this._occlusionDataStorage.occlusionType = value;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
        get: function () {
            return this._occlusionDataStorage.occlusionRetryCount;
        },
        set: function (value) {
            this._occlusionDataStorage.occlusionRetryCount = value;
        },
        enumerable: true,
        configurable: true
    });
    // We also need to update AbstractMesh as there is a portion of the code there
    BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
        var dataStorage = this._occlusionDataStorage;
        if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
            dataStorage.isOccluded = false;
            return false;
        }
        var engine = this.getEngine();
        if (engine.webGLVersion < 2) {
            dataStorage.isOccluded = false;
            return false;
        }
        if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
            dataStorage.isOccluded = false;
            return false;
        }
        if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
            var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
            if (isOcclusionQueryAvailable) {
                var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
                dataStorage.isOcclusionQueryInProgress = false;
                dataStorage.occlusionInternalRetryCounter = 0;
                dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
            }
            else {
                dataStorage.occlusionInternalRetryCounter++;
                if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
                    dataStorage.isOcclusionQueryInProgress = false;
                    dataStorage.occlusionInternalRetryCounter = 0;
                    // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
                    // if strict continue the last state of the object.
                    dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
                }
                else {
                    return false;
                }
            }
        }
        var scene = this.getScene();
        if (scene.getBoundingBoxRenderer) {
            var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
            if (!this._occlusionQuery) {
                this._occlusionQuery = engine.createQuery();
            }
            engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
            occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
            engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
            this._occlusionDataStorage.isOcclusionQueryInProgress = true;
        }
        return dataStorage.isOccluded;
    };
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.engine.occlusionQuery.js.map


var BABYLON;
(function (BABYLON) {
    /**
     * Class used to generate noise procedural textures
     */
    var NoiseProceduralTexture = /** @class */ (function (_super) {
        __extends(NoiseProceduralTexture, _super);
        /**
         * Creates a new NoiseProceduralTexture
         * @param name defines the name fo the texture
         * @param size defines the size of the texture (default is 256)
         * @param scene defines the hosting scene
         * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
         * @param generateMipMaps defines if mipmaps must be generated (true by default)
         */
        function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
            if (size === void 0) { size = 256; }
            if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
            var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
            _this._time = 0;
            /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
            _this.brightness = 0.2;
            /** Defines the number of octaves to process */
            _this.octaves = 3;
            /** Defines the level of persistence (0.8 by default) */
            _this.persistence = 0.8;
            /** Gets or sets animation speed factor (default is 1) */
            _this.animationSpeedFactor = 1;
            _this.autoClear = false;
            _this._updateShaderUniforms();
            return _this;
        }
        NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
            var scene = this.getScene();
            if (!scene) {
                return;
            }
            this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
            this.setFloat("brightness", this.brightness);
            this.setFloat("persistence", this.persistence);
            this.setFloat("timeScale", this._time);
        };
        NoiseProceduralTexture.prototype._getDefines = function () {
            return "#define OCTAVES " + (this.octaves | 0);
        };
        /** Generate the current state of the procedural texture */
        NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
            this._updateShaderUniforms();
            _super.prototype.render.call(this, useCameraPostProcess);
        };
        /**
         * Serializes this noise procedural texture
         * @returns a serialized noise procedural texture object
         */
        NoiseProceduralTexture.prototype.serialize = function () {
            var serializationObject = {};
            serializationObject.customType = "BABYLON.NoiseProceduralTexture";
            serializationObject.brightness = this.brightness;
            serializationObject.octaves = this.octaves;
            serializationObject.persistence = this.persistence;
            serializationObject.animationSpeedFactor = this.animationSpeedFactor;
            serializationObject.size = this.getSize().width;
            serializationObject.generateMipMaps = this._generateMipMaps;
            return serializationObject;
        };
        /**
         * Creates a NoiseProceduralTexture from parsed noise procedural texture data
         * @param parsedTexture defines parsed texture data
         * @param scene defines the current scene
         * @param rootUrl defines the root URL containing noise procedural texture information
         * @returns a parsed NoiseProceduralTexture
         */
        NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
            var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
            texture.brightness = parsedTexture.brightness;
            texture.octaves = parsedTexture.octaves;
            texture.persistence = parsedTexture.persistence;
            texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
            return texture;
        };
        return NoiseProceduralTexture;
    }(BABYLON.ProceduralTexture));
    BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.noiseProceduralTexture.js.map

var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var BABYLON;
(function (BABYLON) {
    /**
     * This can helps recording videos from BabylonJS.
     * This is based on the available WebRTC functionalities of the browser.
     *
     * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
     */
    var VideoRecorder = /** @class */ (function () {
        /**
         * Create a new VideoCapture object which can help converting what you see in Babylon to
         * a video file.
         * @param engine Defines the BabylonJS Engine you wish to record
         * @param options Defines options that can be used to customized the capture
         */
        function VideoRecorder(engine, options) {
            if (options === void 0) { options = null; }
            if (!VideoRecorder.IsSupported(engine)) {
                throw "Your browser does not support recording so far.";
            }
            var canvas = engine.getRenderingCanvas();
            if (!canvas) {
                throw "The babylon engine must have a canvas to be recorded";
            }
            this._canvas = canvas;
            this._canvas.isRecording = false;
            this._options = __assign({}, VideoRecorder._defaultOptions, options);
            var stream = this._canvas.captureStream(this._options.fps);
            this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
            this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
            this._mediaRecorder.onerror = this._handleError.bind(this);
            this._mediaRecorder.onstop = this._handleStop.bind(this);
        }
        /**
         * Returns wehther or not the VideoRecorder is available in your browser.
         * @param engine Defines the Babylon Engine to check the support for
         * @returns true if supported otherwise false
         */
        VideoRecorder.IsSupported = function (engine) {
            var canvas = engine.getRenderingCanvas();
            return (!!canvas && typeof canvas.captureStream === "function");
        };
        Object.defineProperty(VideoRecorder.prototype, "isRecording", {
            /**
             * True wether a recording is already in progress.
             */
            get: function () {
                return !!this._canvas && this._canvas.isRecording;
            },
            enumerable: true,
            configurable: true
        });
        /**
         * Stops the current recording before the default capture timeout passed in the startRecording
         * functions.
         */
        VideoRecorder.prototype.stopRecording = function () {
            if (!this._canvas || !this._mediaRecorder) {
                return;
            }
            if (!this.isRecording) {
                return;
            }
            this._canvas.isRecording = false;
            this._mediaRecorder.stop();
        };
        /**
         * Starts recording the canvas for a max duration specified in parameters.
         * @param fileName Defines the name of the file to be downloaded when the recording stop. If null no automatic download will start and you can rely on the promise to get the data back.
         * @param maxDuration Defines the maximum recording time in seconds.
         * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
         * @return a promise callback at the end of the recording with the video data in Blob.
         */
        VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
            var _this = this;
            if (fileName === void 0) { fileName = "babylonjs.webm"; }
            if (maxDuration === void 0) { maxDuration = 7; }
            if (!this._canvas || !this._mediaRecorder) {
                throw "Recorder has already been disposed";
            }
            if (this.isRecording) {
                throw "Recording already in progress";
            }
            if (maxDuration > 0) {
                setTimeout(function () {
                    _this.stopRecording();
                }, maxDuration * 1000);
            }
            this._fileName = fileName;
            this._recordedChunks = [];
            this._resolve = null;
            this._reject = null;
            this._canvas.isRecording = true;
            this._mediaRecorder.start(this._options.recordChunckSize);
            return new Promise(function (resolve, reject) {
                _this._resolve = resolve;
                _this._reject = reject;
            });
        };
        /**
         * Releases internal resources used during the recording.
         */
        VideoRecorder.prototype.dispose = function () {
            this._canvas = null;
            this._mediaRecorder = null;
            this._recordedChunks = [];
            this._fileName = null;
            this._resolve = null;
            this._reject = null;
        };
        VideoRecorder.prototype._handleDataAvailable = function (event) {
            if (event.data.size > 0) {
                this._recordedChunks.push(event.data);
            }
        };
        VideoRecorder.prototype._handleError = function (event) {
            this.stopRecording();
            if (this._reject) {
                this._reject(event.error);
            }
            else {
                throw new event.error();
            }
        };
        VideoRecorder.prototype._handleStop = function () {
            this.stopRecording();
            var superBuffer = new Blob(this._recordedChunks);
            if (this._resolve) {
                this._resolve(superBuffer);
            }
            window.URL.createObjectURL(superBuffer);
            if (this._fileName) {
                BABYLON.Tools.Download(superBuffer, this._fileName);
            }
        };
        VideoRecorder._defaultOptions = {
            mimeType: "video/webm",
            fps: 25,
            recordChunckSize: 3000
        };
        return VideoRecorder;
    }());
    BABYLON.VideoRecorder = VideoRecorder;
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.videoRecorder.js.map

var BABYLON;
(function (BABYLON) {
    BABYLON.Scene.prototype.createDefaultLight = function (replace) {
        if (replace === void 0) { replace = false; }
        // Dispose existing light in replace mode.
        if (replace) {
            if (this.lights) {
                for (var i = 0; i < this.lights.length; i++) {
                    this.lights[i].dispose();
                }
            }
        }
        // Light
        if (this.lights.length === 0) {
            new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
        }
    };
    BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
        if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
        if (replace === void 0) { replace = false; }
        if (attachCameraControls === void 0) { attachCameraControls = false; }
        // Dispose existing camera in replace mode.
        if (replace) {
            if (this.activeCamera) {
                this.activeCamera.dispose();
                this.activeCamera = null;
            }
        }
        // Camera
        if (!this.activeCamera) {
            var worldExtends = this.getWorldExtends();
            var worldSize = worldExtends.max.subtract(worldExtends.min);
            var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
            var camera;
            var radius = worldSize.length() * 1.5;
            // empty scene scenario!
            if (!isFinite(radius)) {
                radius = 1;
                worldCenter.copyFromFloats(0, 0, 0);
            }
            if (createArcRotateCamera) {
                var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
                arcRotateCamera.lowerRadiusLimit = radius * 0.01;
                arcRotateCamera.wheelPrecision = 100 / radius;
                camera = arcRotateCamera;
            }
            else {
                var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
                freeCamera.setTarget(worldCenter);
                camera = freeCamera;
            }
            camera.minZ = radius * 0.01;
            camera.maxZ = radius * 1000;
            camera.speed = radius * 0.2;
            this.activeCamera = camera;
            var canvas = this.getEngine().getRenderingCanvas();
            if (attachCameraControls && canvas) {
                camera.attachControl(canvas);
            }
        }
    };
    BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
        if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
        if (replace === void 0) { replace = false; }
        if (attachCameraControls === void 0) { attachCameraControls = false; }
        this.createDefaultLight(replace);
        this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
    };
    BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
        if (pbr === void 0) { pbr = false; }
        if (scale === void 0) { scale = 1000; }
        if (blur === void 0) { blur = 0; }
        if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
        if (!environmentTexture) {
            BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
            return null;
        }
        if (setGlobalEnvTexture) {
            if (environmentTexture) {
                this.environmentTexture = environmentTexture;
            }
        }
        // Skybox
        var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
        if (pbr) {
            var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
            hdrSkyboxMaterial.backFaceCulling = false;
            hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
            if (hdrSkyboxMaterial.reflectionTexture) {
                hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
            }
            hdrSkyboxMaterial.microSurface = 1.0 - blur;
            hdrSkyboxMaterial.disableLighting = true;
            hdrSkyboxMaterial.twoSidedLighting = true;
            hdrSkybox.infiniteDistance = true;
            hdrSkybox.material = hdrSkyboxMaterial;
        }
        else {
            var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
            skyboxMaterial.backFaceCulling = false;
            skyboxMaterial.reflectionTexture = environmentTexture.clone();
            if (skyboxMaterial.reflectionTexture) {
                skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
            }
            skyboxMaterial.disableLighting = true;
            hdrSkybox.infiniteDistance = true;
            hdrSkybox.material = skyboxMaterial;
        }
        return hdrSkybox;
    };
    BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
        if (BABYLON.EnvironmentHelper) {
            return new BABYLON.EnvironmentHelper(options, this);
        }
        return null;
    };
    BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
        if (webVROptions === void 0) { webVROptions = {}; }
        return new BABYLON.VRExperienceHelper(this, webVROptions);
    };
})(BABYLON || (BABYLON = {}));

//# sourceMappingURL=babylon.sceneHelpers.js.map

BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
    
var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
globalObject["BABYLON"] = BABYLON;
//backwards compatibility
if(typeof earcut !== 'undefined') {
    globalObject["Earcut"] = {
        earcut: earcut
    };
}

    return BABYLON;
});
